2

単純な型階層の一部である別のインスタンスの型に基づいて、クラスのインスタンスをインスタンス化したいと考えています。

public abstract class Base
{
}

public class Derived1 : Base
{
}

public class Derived2 : Base
{
}

これは、次のコードで簡単に実行できます

Base d1 = new Derived1();

Base d2;

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

ただし、if...else if...(たとえば) リフレクションを使用して (私の例では) のコンストラクターを取得し、それを使用して、発生する可能性d1のある型の別のインスタンスをインスタンス化することにより、チェーンなしでこれを達成することは可能ですか?d1

4

2 に答える 2

9
d2 = (Base)Activator.CreateInstance(d1.GetType());
于 2013-08-08T13:37:58.990 に答える
1

Factory Method 設計パターンを使用できます。

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();
    }
}

それで:

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

リフレクションよりも手間がかかりますが、移植性が高く高速です。

于 2013-08-08T13:41:16.770 に答える