简体   繁体   中英

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

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")) . But make sure you give it full type name (with namespace like "System.Int64").

Reference: 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.

Type.GetType expects a assembly-qualified name:

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."

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"

(I got that with Console.WriteLine(typeof(string).AssemblyQualifiedName); )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM