Deep Copy using Reflection in an Extension Method for Silverlight?

后端 未结 3 1152
再見小時候
再見小時候 2020-12-17 05:38

So I\'m trying to find a generic extension method that creates a deep copy of an object using reflection, that would work in Silverlight. Deep copy using serialization is no

3条回答
  •  不思量自难忘°
    2020-12-17 06:00

    Required Namespaces:

    using System.Reflection;
    using System.Collections.Generic;
    

    Method:

        private readonly static object _lock = new object();
    
        public static T cloneObject(T original, List propertyExcludeList)
        {
            try
            {
                Monitor.Enter(_lock);
                T copy = Activator.CreateInstance();
                PropertyInfo[] piList = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (PropertyInfo pi in piList)
                {
                    if (!propertyExcludeList.Contains(pi.Name))
                    {
                        if (pi.GetValue(copy, null) != pi.GetValue(original, null))
                        {
                            pi.SetValue(copy, pi.GetValue(original, null), null);
                        }
                    }
                }
                return copy;
            }
            finally
            {
                Monitor.Exit(_lock);
            }
        }
    

    This is not specific to Silverlight in any way - it is just plain Reflection.

    As written it will only work with objects that have a parameterless constructor. To use objects that require constructor parameters, you will need to pass in an object[] with the parameters, and use a different overload of the Activator.CreateInstance method e.g.

    T copy = (T)Activator.CreateInstance(typeof(T), initializationParameters);
    

    The propertyExcludeList parameter is a list of property names that you wish to exclude from the copy, if you want to copy all properties just pass an empty list e.g.

    new List()
    

提交回复
热议问题