C# memcpy equivalent

后端 未结 8 638
野的像风
野的像风 2020-12-11 05:11

I have 2 objects from the same type and i would like to shallow copy one state to the other. In C++ i have memcpy which is great. How can i do it in C#? The MemberwiseClone(

8条回答
  •  执笔经年
    2020-12-11 05:23

    In C# (and in C++ too), there is no difference between "new object" and "a copy of existing object" as long as all their members equal to each other.

    Given:

    Int32 a = 5;
    

    , both operations:

    Int32 b = 5;
    Int32 b = a;
    

    yield the same result.

    As stated in MSDN reference:

    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.

    , i.e. it does just the same as memcpy() in C++

提交回复
热议问题