mardi 27 octobre 2015

System.StackOverflowException when cloning an object using reflection

I am coding a C# forms application, and I am using the following code to clone on object:

public static class ObjectExtension
{
    public static object CloneObject(this object objSource)
    {
        //Get the type of source object and create a new instance of that type
        Type typeSource = objSource.GetType();
        object objTarget = Activator.CreateInstance(typeSource);

        //Get all the properties of source object type
        PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        //Assign all source property to taget object 's properties
        foreach (PropertyInfo property in propertyInfo)
        {
            //Check whether property can be written to
            if (property.CanWrite)
            {
                //check whether property type is value type, enum or string type
                if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
                {
                    property.SetValue(objTarget, property.GetValue(objSource, null), null);
                }
                //else property type is object/complex types, so need to recursively call this method until the end of the tree is reached
                else
                {
                    object objPropertyValue = property.GetValue(objSource, null);
                    if (objPropertyValue == null)
                    {
                        property.SetValue(objTarget, null, null);
                    }
                    else
                    {
                        property.SetValue(objTarget, objPropertyValue.CloneObject(), null);
                    }
                }
            }
        }
        return objTarget;
    }
}

Some of my objects have parent objects and these parent objects have collections. As such, I am getting the following exception:

An unhandled exception of type 'System.StackOverflowException' occurred in CustomWebpageObjectCreator.exe

How can I prevent this from happening?

Is it possible to decorate some specific properties in an object with an attribute, such that the CloneObject code will not try and clone the property? If so, can someone please help me with the code to do this? If not, how should I modify my code?





Aucun commentaire:

Enregistrer un commentaire