Why is MemberwiseClone defined in System.Object protected?

前端 未结 4 451
礼貌的吻别
礼貌的吻别 2020-12-18 21:42

I\'m wondering why MemberwiseClone is defined as protected. This means that only derived types can access it. What is the problem if it was defined as public?

4条回答
  •  甜味超标
    2020-12-18 22:12

    Literally noone is preventing you from exposing it as public in your own class if you want to. It highly depends on what you want to achieve. For example MemberwiseClone it does not execute any ctor. So it would be more usefull to use Activator.CreateInstance.

    Considering what MemberwiseClone actually does, there is in almost every case no need to expose it.

    protected unsafe object MemberwiseClone()
    {
        object clone = RuntimeHelpers.AllocateUninitializedClone(this);
     
        // copy contents of "this" to the clone
        nuint byteCount = RuntimeHelpers.GetRawObjectDataSize(clone);
        ref byte src = ref this.GetRawData();
        ref byte dst = ref clone.GetRawData();
     
        if (RuntimeHelpers.GetMethodTable(clone)->ContainsGCPointers)
            Buffer.BulkMoveWithWriteBarrier(ref dst, ref src, byteCount);
        else
            Buffer.Memmove(ref dst, ref src, byteCount);
        return clone;
    }
    

    you can find it here:

提交回复
热议问题