Best way to create an instance of run-time determi

2020-06-02 02:08发布

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.

7条回答
劫难
2楼-- · 2020-06-02 02:42
public void SomeMethod()
{
    object x =Activator.CreateInstance(this.GetType());
}

This should create a new instance, on the other hand I wonder the why you trying to do this.

查看更多
登录 后发表回答