Creating an instance of a class with the same type

2019-07-20 09:48发布

问题:

I would like to instantiate an instance of a class based on the type of another instance that is part of a simple type hierarchy.

public abstract class Base
{
}

public class Derived1 : Base
{
}

public class Derived2 : Base
{
}

This is easy to do with the following code

Base d1 = new Derived1();

Base d2;

if (d1 is Derived1)
{
    d2 = new Derived1();
}
else if (d1 is Derived2)
{
    d2 = new Derived2();
}

However, is it possible to achieve this without an if...else if... chain by (for example) using reflection to get hold of the constructor of d1 (in my example) and using it to instantiate another instance of whatever type d1 might happen to be?

回答1:

d2 = (Base)Activator.CreateInstance(d1.GetType());


回答2:

You can use Factory Method design pattern:

public abstract class Base
{
    public abstract Base New();
}

public class Derived1 : Base
{
    public override Base New()
    {
        return new Derived1();
    }
}

public class Derived2 : Base
{
    public override Base New()
    {
        return new Derived2();
    }
}

Then:

Base d1 = new Derived1();
Base d2 = d1.New();

More effort than reflection but also more portable and faster.



标签: c# base-class