繁体   English   中英

为什么不能像其他继承方法 Object class 一样直接使用 MemberwiseClone()? (对于浅拷贝)

[英]Why MemberwiseClone() can not be used directly, like other inherited methods of Object class? (For shallow copy)

可以说我有一些自定义类型:

public class MyClass
{
   public int Age;
}

According to MS documentation here , all classes in .NET are derived from Object, and every method defined in the Object class is available in all objects in the system

Since Object.MemberwiseClone() is part of object class, why I can't do shallow copy just by calling it form instance on my custom class, like "Equals(), GetHashCode(), etc? Why I can't do something像这样:

class Program
{
     static void Main(string[] args)
     {
         MyClass myClass = new MyClass();
         MyClass myClassCopy = (MyClass)myClass.MemberwiseClone();  //Not working!
     }
}

相反,在我看到的所有示例中,我需要明确地实现一些浅拷贝方法,例如:

public class MyClass
{
    public int Age;
    public MyClass ShallowCopy()
    {
        return (MyClass)MemberwiseClone();
    }
}

只有这样,我才能调用这个方法 ShallowCopy()。

[编辑]

我认为这个问题在这里解释了这一点: 为什么在 System.Object 中定义的 MemberwiseClone 受保护? 我需要问将 Object.MemberwiseClone() 设为私有的原因是什么,主要原因是:这里的问题是 MemberwiseClone 只是盲目地复制 state。 在许多情况下,这是不可取的

这是一个protected的方法——大概是为了让每个类的实现来决定成员克隆是否有意义,如果是的话,如何将它公开给调用者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM