What is the method MemberwiseClone() doing?

偶尔善良 提交于 2019-11-28 17:45:57
Bozho

Because the method MemberwiseClone() is doing this for you. See the documentation

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

Whenever you see a method you don't unerstand, you can trace who has declared it (in Visual Studio, I guess), and in turn see its documentation. That makes things pretty obvious most of the time.

supercat

The function MemberwiseClone creates a new objects whose fields are bit-for-bit copies of those in the original structure. It is a necessary part of any inheritable class which allows cloning without use of Reflection or serialization, but it is only a small piece of the overall puzzle.

If you wish to allow cloning within an inheritable class, you should define a protected virtual T BaseClone<T>() cloning method; the base-level class which descends from Object should call base.MemberwiseClone; all other classes should use base.BaseClone<T> to get the new instance and then replace any mutable cloneable fields with clones of the ones in the original object.

I would also recommend defining the following interfaces:

interface ISelf<out T> {T Self();}
interface ICloneable<out T> : ISelf<T> {T Clone();}

That will allow for situations in which a class may have some descendants which can be cloned and some which cannot. Those which can be cloned can expose public cloning methods (which should chain to BaseClone<theirOwnType>). Methods which need cloneable derivatives of the base type can use parameters of type ICloneable<theBaseType>; this will allow them to accept any cloneable derivative of the base type, even if not all such derivatives share a common base class.

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