-4

如何获取对象中存在的所有日期时间类型?

EG 货件对象包含有关货件的所有详细信息,例如托运人名称、收货人名称等。它还包含许多日期时间字段,例如收货日期、运输日期、交货日期等。

我怎样才能得到货件对象的所有日期字段?

4

2 回答 2

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

或者最后,使用反射来迭代属性:

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));
    }
}
于 2012-10-01T08:11:41.563 回答
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

于 2012-10-01T08:03:56.433 回答