简体   繁体   English

如何使用反射递归获取类型的属性?

[英]How to recursively get properties of a type using reflection?

I need to recursively get all DateTime properties of an object.我需要递归获取对象的所有DateTime属性。

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.但是,使用property.GetType().IsClass是不够的,因为即使是字符串或日期属性也是类。

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?如果我向具有DateTime属性的类添加一个接口,然后检查该属性是否实现了该接口,会更好吗?

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.我向具有DateTime属性的类添加了一个接口。 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...
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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