我需要递归获取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
属性的类中,然后检查该属性是否实现了该接口,会更好吗?
我向具有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...
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句