[英]How to invoke Constructors by String in C# (i.e. by Reflection)?
I use the Chart class WPFToolKit and I want to invoke Construtors by String to short the code below 我使用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;
}
After searching I find the code below: 搜索后我找到下面的代码:
Type type = Type.GetType(node.Attributes["type"].Value);
Console.WriteLine(type == null);
ConstructorInfo ctor = type.GetConstructor(new Type[] { });
object instance = ctor.Invoke(new object[]{});
But strangely, the type is always null and I don't why. 但奇怪的是,类型总是为空,我不是为什么。 Could anyone tell me that?
有人能告诉我吗? Thanks.
谢谢。
If your class has a public default constructor, you can use Activator.CreateInstance(Type.GetType("your type"))
. 如果您的类具有公共默认构造函数,则可以使用
Activator.CreateInstance(Type.GetType("your type"))
。 But make sure you give it full type name (with namespace like "System.Int64"). 但请确保为其提供完整的类型名称(使用名称为“System.Int64”的命名空间)。
Reference: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx 参考: http : //msdn.microsoft.com/en-us/library/wccyzw83.aspx
UPDATE: 更新:
If the type is in another assembly, refer to this SO question to know how to get the type. 如果类型在另一个程序集中,请参阅此SO问题以了解如何获取该类型。
Type.GetType
expects a assembly-qualified name: Type.GetType
需要一个程序集限定的名称:
Here is the documentation about it: "The assembly-qualified name of the type to get. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace." 以下是有关它的文档:“要获取的类型的程序集限定名称。如果类型在当前正在执行的程序集中或在Mscorlib.dll中,则提供由其名称空间限定的类型名称就足够了。”
This includes the namespace and the assembly of the type. 这包括命名空间和类型的程序集。 For example the assembly qualified name for the string class is something like this:
例如,字符串类的程序集限定名称是这样的:
"System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" “System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089”
(I got that with Console.WriteLine(typeof(string).AssemblyQualifiedName);
) (我用
Console.WriteLine(typeof(string).AssemblyQualifiedName);
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.