与同类型的现有对象创建一个类的实例 [英] Creating an instance of a class with the same type as an existing object

查看:106
本文介绍了与同类型的现有对象创建一个类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据作为简单类型层次结构一部分的另一个实例的类型来实例化一个类的实例。

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
{
}

Base d1 = new Derived1();

Base d2;

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

但是,如果没有如果... else if ... chain by(例如)使用反射来获得 d1 并且使用它来实例化 d1 的另一个实例可能是?

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?

推荐答案

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

这篇关于与同类型的现有对象创建一个类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆