来自超型的C#克隆 [英] C# clone from supertype
问题描述
抽象超类型动物具有许多子类型,例如猫,狗等.这些子类型仅具有构造函数,并且覆盖在动物中发现的虚拟方法-即它们没有自身的属性或方法.动物园类对动物列表和动物列表有很多引用,但对猫,狗等一无所知,或者永远也不会知道.启用Zoo深度复制的最佳方法是什么?,最好在猫,狗等中很少或没有新代码.
Abstract supertype Animal has many subtypes, Cat, Dog etc. These subtypes have only a constructor and overrides of virtual methods found in Animal - ie they have NO Properties or Methods unique to themselves. Class Zoo has many references to, and Lists of Animals, but does not know about or will ever need to know about Cats, Dogs etc. What is the most best way of enabling deep copying of Zoo? , preferably with little or no new code in Cat, Dog etc.
推荐答案
如果您担心需要创建一个新的 Clone
实现,则只需获取正确的类型(因为<在基类中的code> this 是移动目标),对于覆盖 Animal <的所有类型,您可以使用
Activator.CreateInstance
创建当前类型的新实例./code>:
If your concern is that you need to create a new Clone
implementation, just to get the right type (since the type of this
in a base class is a moving target), you could use Activator.CreateInstance
to create a new instance of the current type, for all types that override Animal
:
var copy = (Animal)Activator.CreateInstance(this.GetType());
copy.HasClaws = this.HasClaws; // copy Animal properties
您需要一个无参数的构造函数才能使此 Activator.CreateInstance
调用正常工作.
You need a parameterless constructor in order to make this Activator.CreateInstance
call work.
这篇关于来自超型的C#克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!