How to Clone Objects

后端 未结 13 1259
北海茫月
北海茫月 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:00

    MemberwiseClone is a good way to do a shallow copy as others have suggested. It is protected however, so if you want to use it without changing the class, you have to access it via reflection. Reflection however is slow. So if you are planning to clone a lot of objects it might be worthwhile to cache the result:

    public static class CloneUtil
    {
        private static readonly Func clone;
    
        static CloneUtil()
        {
            var cloneMethod = typeof(T).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            clone = (Func)cloneMethod.CreateDelegate(typeof(Func));
        }
    
        public static T ShallowClone(T obj) => (T)clone(obj);
    }
    
    public static class CloneUtil
    {
        public static T ShallowClone(this T obj) => CloneUtil.ShallowClone(obj);
    }
    

    You can call it like this:

    Person b = a.ShallowClone();
    

提交回复
热议问题