简体   繁体   English

如何使用反射动态实例化一个类型?

[英]How to instantiate a type dynamically using reflection?

I need to instatiate a C# type dynamically, using reflection. 我需要使用反射动态地实例化一个C#类型。 Here is my scenario: I am writing a base class, which will need to instantiate a certain object as a part of its initialization. 这是我的场景:我正在编写一个基类,它需要将某个对象实例化为其初始化的一部分。 The base class won't know what type of object it is supposed to instantiate, but the derived class will. 基类不知道它应该实例化的对象类型,但派生类将会。 So, I want to have the derived class pass the type to the base class in a base() call. 所以,我希望派生类在base()调用中将类型传递给基类。 The code looks something like this: 代码看起来像这样:

public abstract class MyBaseClass
{
    protected MyBaseClass(Type myType)
    {
         // Instantiate object of type passed in 
         /* This is the part I'm trying to figure out */
    }
}

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass() : base(typeof(Whatever))
    {
    }
}

In other words, the base class is delegating to its derived type the choice of the object type to be instantiated. 换句话说,基类委托其派生类型选择要实例化的对象类型。

Can someone please assist? 有人可以帮忙吗?

Try Activator.CreateInstance(Type) 试试Activator.CreateInstance(Type)

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

You're looking for Activator.CreateInstance 您正在寻找Activator.CreateInstance

object instance = Activator.CreateInstance(myType);

There are are various overloads of this method that can take constructor arguments or other information to find the type (such as names in string form) 此方法有各种重载,可以使用构造函数参数或其他信息来查找类型(例如字符串形式的名称)

You might want to use generics instead: 您可能希望使用泛型:

public abstract class MyBaseClass<T> where T : new()
{
    protected MyBaseClass()
    {
        T myObj = new T();
         // Instantiate object of type passed in 
         /* This is the part I'm trying to figure out */
    }
}

public class MyDerivedClass : MyBaseClass<Whatever>
{
    public MyDerivedClass() 
    {
    }
}

The where T : new() is required to support the new T() construct. 需要where T : new()来支持new T()构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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