-1

我有以下问题:

public class MyType
{
    public void method(int a, params object[] p){} 
    public void MyType()
    {
        method(5);
    }
}

当我使用构造函数时,一切都很好,但是当我尝试使用时Activator.CreateInstance(MyType);

void Factory()
{
    string componentPath = "MyType.dll";
    Assembly component = Assembly.LoadFrom(componentPath);
    Type myType= component.GetType("MyType");
    Activator.CreateInstance(myType);
}

MyType.method(int32)它失败,未找到异常。重要的是要注意,在我添加params object[] p到方法之前,一切正常。

谢谢你。

4

2 回答 2

3

如果您使用带有可选参数的方法或方法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).

于 2011-05-25T08:19:06.577 回答
0

这是行不通的,因为您必须在对 method() 的调用中传递至少 2 个参数。params修饰符并不意味着“可选” 。

于 2011-05-25T08:04:38.657 回答