如何使用反射动态实例化类型? [英] How to instantiate a type dynamically using reflection?

查看:41
本文介绍了如何使用反射动态实例化类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用反射动态地建立一个 C# 类型.这是我的场景:我正在编写一个基类,它需要实例化某个对象作为其初始化的一部分.基类不知道它应该实例化什么类型的对象,但派生类会.所以,我想让派生类在 base() 调用中将类型传递给基类.代码如下所示:

I need to instatiate a C# type dynamically, using reflection. 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. 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.

有人可以帮忙吗?

推荐答案

Try Activator.CreateInstance(Type)

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

这篇关于如何使用反射动态实例化类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆