2012-10-01 150 views
-4

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

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

如何获取所有日期字段装运对象?

+4

请告诉我你的代码呢? – BugFinder

回答

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

关于SoC的思考,我会推荐使用'返回列表给你'的方法! – Aphelion

+0

@Aphelion - 我真的不知道哪里有SoC问题在这里。属性已经属于该对象,因此没有理由为什么该对象无法返回它们的列表(无论出于何种原因)。由于OP没有真正说出他们需要日期的原因(或者有多少日期),所以很难看出哪种解决方案最适合他们。 – James

+0

很好的解释。谢谢。我必须同意,很难看到需要什么。我们甚至不确定我们是否可以修改对象来提供列表。 – Aphelion