如何获取对象中存在的所有日期时间类型?
E.G。装运对象包含有关装运的所有详细信息,如托运人姓名,收货人等。它还包含许多日期时间字段,如收货日期,运输日期,交货日期等。
如何获取货件对象的所有日期字段?
答案 0 :(得分:1)
最简单的方法是直接访问属性,例如
var receivedDate = shipment.ReceivedDate;
var transportedDate = shipment.DeliveryDate;
...
另一种方法是让你的Shipment
对象为你返回列表,例如
public Dictionary<string, DateTime> Dates
{
get
{
return new Dictionary<string, DateTime>()
{
new KeyValuePair<string, DateTime>("ReceivedDate", ReceivedDate),
new KeyValuePair<string, DateTime>("DeliveryDate", DeliveryDate),
...
}
}
}
...
foreach (var d in shipment.Dates)
{
Console.WriteLine(d.Key, d.Value);
}
或者最后,使用Reflection来迭代属性:
public Dictionary<string, DateTime> Dates
{
get
{
return from p in this.GetType().GetProperties()
where p.PropertyType == typeof(DateTime)
select new KeyValuePair<string, DateTime>(p.Name, (DateTime)p.GetValue(this, null));
}
}
答案 1 :(得分:0)
您可以使用反射。
Type myClassType = typeof(MyClass); // or object.GetType()
var dateTimeProperties = from property in myClassType.GetProperties()
where property.PropertyType == typeof(DateTime)
select property;
了解更多有关.net中反射的内容
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.aspx