创建运行时确定类型实例的最佳方式 [英] Best way to create an instance of run-time determined type
问题描述
我有一个实例方法,尽管它是在BaseClass上执行的对象可以通过派生类的实例调用。我需要在方法中创建与这个
相同类型的另一个实例。重载每个派生类的方法是不实际的,因为它是相当的参与,并且更有效地保持单一的实现。
public class BaseClass
{
//构造函数+属性+方法等
public SomeMethod()
{
// some code
DerivedClass d = new DerivedClass(); //在运行时理想地确定DerivedClass类型
}
}
我读了一些关于反思或使用动态关键字,但是我没有这方面的经验。
你是寻找 Activator.CreateInstance
(还有其他重载,例如这一个,接受构造函数参数)。所以你可以写
var anotherOneLikeMe = Activator.CreateInstance(this.GetType());
这里可能有一个问题, anotherOneLikeMe
将被打包为对象
,所以除非你打算将它转换为一个公共的基类(例如 BaseClass
在你的例子中)没有太多的事情可以用它。
What's the best way (in .NET 4) to create an instance of a type determined at runtime.
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.
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());
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屋!