简体   繁体   中英

How do I recursively loop through a reflected type and set it's child-object values?

For my data layer, I have a L2Sql assembly which contains all my entities. These entities are mostly related to each other. The problem is that because of our internal development standards, we want to set certain properties to specific values once the objects instances are created.

My idea is to recursively scan my related objects (Person.ContactDetails.Address), set the property values and then return the parent object back (Person) for further processing.

I've got the recursion going, but unfortunately it seems to only return the last child in the heirachy (Address) instead of Person.

Here's my code:

private Type SetDefaultTypeValues(Type t, object o, Type parentType)
{
    Type theType = t;
    PropertyInfo[] fields = theType.GetProperties();

    foreach (PropertyInfo fi in fields)
    {
        switch (fi.Name)
        {
            case "CreateDate":
                fi.SetValue(o, DateTime.Now, null);
                break;
            case "ModifyDate":
                fi.SetValue(o, DateTime.Now, null);
                break;
            case "Active":
                fi.SetValue(o, true, null);
                break;
            default:
                if (fi.PropertyType == typeof(DateTime))
                {
                    fi.SetValue(o, new DateTime(1900, 01, 01, 12, 0, 0), null);
                }
                break;
        }

        if (fi.PropertyType.FullName.StartsWith("whatever.arme.Domain.Entities") && fi.PropertyType != parentType) // This is to ignore properties of the child which contain Parent references
        {
            var obj = fi.GetValue(o, null);
            if (obj == null)
                obj = Assembly.GetAssembly(theType).CreateInstance(fi.PropertyType.FullName);
            theType = SetDefaultTypeValues(fi.PropertyType, obj, theType); // I imagine the problem lies between here...
        }
    }
    return theType; // ... and here?
}

Why is my parent object not returning to the originating caller, and returns a different type of object instead?

您应该返回t而不是theType ,因为调用属性时,它会用SetDefaultTypeValues的返回值覆盖theType

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM