如何在C#中通过String调用构造函数(即通过Reflection)?

Cue*_*ero 3 c# reflection wpf

我使用Chart类WPFToolKit,我想通过String调用Construtors来缩短下面的代码

switch (node.Attributes["type"].Value)
{
    case "ColumnSeries":
        ans = new ColumnSeries();
        break;
    case "PieSeries":
        ans = new PieSeries();
        break;
    case "AreaSeries":
        ans = new AreaSeries();
        break;
    case "BarSeries":
        ans = new BarSeries();
        break;
    case "LineSeries":
        ans = new LineSeries();
        break;
}
Run Code Online (Sandbox Code Playgroud)

搜索后我找到下面的代码:

Type type = Type.GetType(node.Attributes["type"].Value);
Console.WriteLine(type == null);
ConstructorInfo ctor = type.GetConstructor(new Type[] { });
object instance = ctor.Invoke(new object[]{});
Run Code Online (Sandbox Code Playgroud)

但奇怪的是,类型总是为空,我不是为什么.有人能告诉我吗?谢谢.

pra*_*nth 6

如果您的类具有公共默认构造函数,则可以使用Activator.CreateInstance(Type.GetType("your type")).但请确保为其提供完整的类型名称(使用名称为"System.Int64"的命名空间).

参考:http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

更新:

如果类型在另一个程序集中,请参阅此SO问题以了解如何获取该类型.