我使用 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;
}
经过搜索我找到了下面的代码:
Type type = Type.GetType(node.Attributes["type"].Value);
Console.WriteLine(type == null);
ConstructorInfo ctor = type.GetConstructor(new Type[] { });
object instance = ctor.Invoke(new object[]{});
但奇怪的是,该类型始终为空,我不明白为什么。谁能告诉我吗? 谢谢。
最佳答案
如果您的类有公共(public)默认构造函数,您可以使用 Activator.CreateInstance(Type.GetType("your type"))
。但请确保为它提供完整的类型名称(命名空间如“System.Int64”)。
引用:http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
更新:
如果类型在另一个程序集中,请参阅 this SO question了解如何获取类型。
关于c# - 如何在 C# 中通过字符串调用构造函数(即通过反射)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557807/