简体   繁体   中英

How to recursively get properties of a type using reflection?

I need to recursively get all DateTime properties of an object.

Currently I'm doing:

public static void GetDates(this object value)
{
    var properties = value.GetType().GetProperties();

    foreach (var property in properties)
    {
        if (property.GetType().IsClass)
        {
            property.SetDatesToUtc();
        }
        else
        {
            if (property.GetType() == typeof(DateTime))
            {
                //Do something...
            }
        }
    }
}

However, using property.GetType().IsClass is not enough as even strings or date properties are classes.

Is there a way to get properties that are actual classes?

Would it be better if I add an interface to the classes that have DateTime properties and then check if that property implements that interface?

You are on the right track, but I think your logic is a little reversed. You should be changing date times, and running the same method on everything else:

public static void GetDates(this object value)
{
    if(value == null) //if this object is null, you need to stop
    {
        return;
    }
    var properties = value.GetType().GetProperties();
    foreach(PropertyInfo property in properties)
    {
        //if the property is a datetime, do your conversion
        if(property.GetType() == typeof(DateTime))
        {
            //do your conversion here
        }
        //otherwise get the value of the property and run the same logic on it
        else
        {
            property.GetValue(value).GetDates(); // here is your recursion
        }
    }
}

I added an interface to the classes that have a DateTime property. So method changes to:

public static void GetDates(this object value)
{
    var properties = value.GetType().GetProperties();
    foreach (var property in properties)
    {
        if (typeof(IHasDateProperty).IsAssignableFrom(property.PropertyType))
        {
            property.SetDatesToUtc();
        }
        else
        {
            if (property.GetType() == typeof(DateTime))
            {
                //Do something...
            }
        }
    }
}

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