2013-01-02 233 views
0

可能重复:
Activator.CreateInstance - How to create instances of classes that have parameterized constructors非默认构造函数

我想知道如何不使用默认的构造函数在运行时创建确定的类型的对象。

也就是说,我有BaseClass和各种子类。

Type type; //this variable will be one of the child classes 
BaseClass base = Activator.CreateInstance(type); 

这允许我创建一个具有默认构造函数的子类对象,但我想调用一个特定的构造函数。我知道所有的子类都有一个构造函数需要一定的参数,所以我不担心那个构造函数不存在。我发现this的问题,但最好的我可以到那里是一个单一的字符串参数。这是可行的吗?

+0

http://stackoverflow.com/questions/1288310/activator-createinstance-how-to-创建-实例-的类 - 即具备的,paramete#答案-1288333 – xandercoded

回答

3

三个选项:

第三个选项要求每次添加一个新的类型,当然,时间来改变你的工厂代码 - 但它只是一个单线。

我个人喜欢第一个选项,因为它给了你最大的控制权(而不是依靠Activator.CreateInstance在执行时找到最好的匹配构造函数) - 如果这是对性能敏感的代码,你可以构建一个代表字典在执行时通过发现构造函数,然后使用表达式树。 (据我所知,你不能使用Delegate.CreateDelegate从构造函数构建代理,这有点烦人。)

2

您可以使用Activator.CreateInstance(Type, Object[])重载来执行此操作。它会根据提供的参数调用最可靠的构造函数。

例如:

public class Test{ 
public Test(){ 
    Console.WriteLine("Defaul ctor"); 
} 

public Test(int i){ 
    Console.WriteLine("Test(int)"); 
} 

public Test(int i, string s){ 
    Console.WriteLine("Test(int, string)"); 
} 
} 

public static void Main() 
{ 
    var o1 = Activator.CreateInstance(typeof(Test)); 
    var o2 = Activator.CreateInstance(typeof(Test), 1); 
    var o3 = Activator.CreateInstance(typeof(Test), 1, "test"); 
}