繁体   English   中英

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

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

我需要递归获取对象的所有DateTime属性。

目前我正在做:

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...
            }
        }
    }
}

但是,使用property.GetType().IsClass是不够的,因为即使是字符串或日期属性也是类。

有没有办法获取实际类的属性?

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

你在正确的轨道上,但我认为你的逻辑有点颠倒。 您应该更改日期时间,并在其他所有内容上运行相同的方法:

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
        }
    }
}

我向具有DateTime属性的类添加了一个接口。 所以方法改为:

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