如果您使用带有可选参数的方法或方法params
来传递可变数量的参数,那么您所做的是告诉编译器当您调用该方法时,它会为您插入必要的参数吗? 可选参数和 params 数组被插入到调用代码中,而不是被调用代码中。(有关可选参数的详细说明,请参阅Eric Lipperts 的一篇博客文章)。
您没有使用 C# 编译器,反射 API 不会为您插入这些参数。例如,您不仅可以通过反射进行测试,还可以使用两个程序集进行测试:Assembly A declares method(int X)
; 它被编译并且 dll 被程序集 B 引用。这个程序集 B 包含对method(42)
. 这很好用!现在,如果您重新编译程序集 A 并将签名更改method(int X, object bla=null)
为or method(int X, params object[] blas)
,那么程序集 B 将停止工作 - 它包含无效调用。即便如此,程序集 B 的源代码仍然可以——您只需要重新编译即可。
Reflection simply happens not to do any of the optional parameter magic for you. It could, certainly - but it doesn't. While reflection doesn't support this, the DLR does, which brings me to the following...
Workaround: Try using the C# keyword dynamic
, if possible (which for constructors, it isn't AFAIK) - that attempts to emulate C# calling conventions more closely and supports stuff like optional and named parameters. You may need to change the way your API is set up, however to use methods rather than constructors. It's hard to give more precise advice without seeing actual code.
Alternatively: You may be trying to load plugins, by the looks of it. .NET has some premade infrastructure to help you with this: Add-ins and Extensibility, which may make your task easier.
(Note: your example code is incomplete - I'm making a slight guess that method
is in reality a constructor, but you should really post the actual code or at least a snippet that actually fails).