Creating an instance of a class with the same type as an existing object

拥有回忆 提交于 2019-12-24 00:05:21

问题


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.



来源:https://stackoverflow.com/questions/18127495/creating-an-instance-of-a-class-with-the-same-type-as-an-existing-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!