How to Clone Objects

后端 未结 13 1241
北海茫月
北海茫月 2020-11-30 04:36

When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a wil

13条回答
  •  死守一世寂寞
    2020-11-30 05:14

    Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:

    public static T Clone(this T obj)
    {
        var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    
        return (T)inst?.Invoke(obj, null);
    }
    

    Usage:

    var clone = myObject.Clone();
    

提交回复
热议问题