C # Recursive reflection and generic lists setting default properties

I am trying to use reflection to achieve the following:

I need a method in which I pass an object, and this method will recursively create an object with child objects and set properties with default values. I need an entire instance of the object, going to as many levels as necessary.

this method should be able to process an object with several properties that will be shared lists of other objects.

Here is my sample code (I get a parameter counter mismatch exception when I get an object containing List<AnotherSetObjects>:

private void SetPropertyValues(object obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))
        {
            Type propType = property.PropertyType;

            var subObject = Activator.CreateInstance(propType);
            SetPropertyValues(subObject);
            property.SetValue(obj, subObject, null);
        }
        else if (property.PropertyType == typeof(string))
        {
            property.SetValue(obj, property.Name, null);
        }
        else if (property.PropertyType == typeof(DateTime))
        {
            property.SetValue(obj, DateTime.Today, null);
        }
        else if (property.PropertyType == typeof(int))
        {
            property.SetValue(obj, 0, null);
        }
        else if (property.PropertyType == typeof(decimal))
        {
            property.SetValue(obj, 0, null);
        }
    }
}

thank

+3
source share
2

, property.PropertyType.IsGeneric, . , property.PropertyType.IsArray.

, . , . - IList.

bool isList(object data)
{
    System.Collections.IList list = data as System.Collections.IList;
    return list != null;
}

...
if (isList(obj)) {
    //do stuff that take special care of object which is a List
    //It will be true for generic type lists too!
}
+1

:)

, "BusinessObjects" ,

if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))

:

System.Collections.Generic.List`1[[ConsoleApplication92.XXXBusinessObjects, ConsoleApplication92, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

, . Item SomeBusinessObjects. , . :

obj.ListProperty.Item = new SomeBusinessObject();

, ,

obj.ListProperty[0] = new SomeBusinessObject();

, .

, , :)

0

Source: https://habr.com/ru/post/1741284/


All Articles