创建运行时确定类型的实例最好的方法 [英] Best way to create an instance of run-time determined type

查看:130
本文介绍了创建运行时确定类型的实例最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的方式(在.NET 4中),以创建在运行时确定一个类型的实例。

What's the best way (in .NET 4) to create an instance of a type determined at runtime.

我有一个实例方法,尽管作用于BaseClass的对象可以通过它的派生类的实例调用。我需要对方法中创建同一类型的另一个实例为这个。重载方法每个派生类是不实际的,因为它是相当复杂的,将被更有效地保持单一的实现。

I have an instance method which although acting on a BaseClass object may be called by instances of its derived classes. I require to create another instance of the same type as this within the method. Overloading the Method for each derived class is not practical as it is fairly involved and would be more efficient to keep to the single implementation.

public class BaseClass
{
     //constructors + properties + methods etc

     public SomeMethod()
     {
          //some code

          DerivedClass d = new DerivedClass(); //ideally determine the DerivedClass type at run-time
     }
}



我读过一些关于反射或使用动态关键字,但我没有这些经验。

I've read a bit about reflection or using the dynamic keyword but i don't have experience with these.

推荐答案

您是寻找 Activator.CreateInstance (有也有其他重载,如这一个接受构造函数的参数)。所以,你可以写

You are looking for Activator.CreateInstance (there are also other overloads, such as this one that accepts constructor arguments). So you could write

var anotherOneLikeMe = Activator.CreateInstance(this.GetType());

有可能在这里是一个问题,即 anotherOneLikeMe 将被分类为对象,所以除非你打算把它转换为一个共同的基类(如的BaseClass 在你的例子)没有太多,你可以用它做。

There may be a problem here in that anotherOneLikeMe is going to be typed as object, so unless you intend to cast it to a common base class (e.g. BaseClass in your example) there's not much that you can do with it.

这篇关于创建运行时确定类型的实例最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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