获取对象类型并相应地分配值

我有一个arraylist,它在其中获得不同类型的值 ,第一个值 – > 字符串 ,第二个值 – > datetime ,第三个值 – > 布尔值和第四个值是int ,我如何找到它们的类型并相应地分配这些值,任何感谢帮助:)

这是我的代码:

foreach (object obj in lstTop) { if(obj.GetType() == string) {do this...) else if(obj.GetType() == DateTime) {do this....} else if(obj.GetType() == bool) {do this....} else if(obj.GetType() == Int) {do this....} } 

谢谢大家, 我的最终守则:

 string Subscription = ""; DateTime issueFirst; DateTime issueEnd; foreach (object obj in lstTop) { ///Type t = obj.GetType(); if (obj is string) Subscription += obj + ","; else if (obj is DateTime) { Subscription += Convert.ToDateTime(obj).ToShortDateString() + ","; } /// else if (t == typeof(DateTime)) } return ("User Authenticated user name: " + userName + ", Subscription: " + Subscription); 

 foreach (object obj in lstTop) { if(obj is string) {do this.....} else if(obj is DateTime) {do this.....} else if(obj is bool) {do this.....} else if(obj is Int) {do this.....} else { // always have an else in case it falls through throw new Exception(); } } 

.Net 2.0中的ArrayLists几乎总是错误的方法。 即使您不知道列表将包含什么,您最好使用通用List因为它可以与其他人通信,列表实际上可以包含任何内容,而不仅仅是.Net 1.1中遗留的内容程序员。

除此之外, is关键字应该做你想要的:

 if (obj is string) // do this else if (obj is DateTime) // do this // ... 

更新我知道这是旧的,但它今天在我的通知中出现。 再次阅读它,我发现另一个很好的方法是通过重载函数的类型解析:

 void DoSomething(string value) { /* ... */ } void DoSomething(DateTime value) { /* ... */ } DoSomething(obj); 

最简单的解决方案是不使用循环,因为您确切知道列表中的内容。

 string myString = (string) lstTop[0]; DateTime myDate = (DateTime) lstTop[1]; bool myBool = (bool) lstTop[2]; int myInt = (int) lstTop[3]; 

如果列表中只包含每种类型的一个值,则可以将其存储在Dictionary (如果使用ArrayList不是特定要求),只需根据请求的类型检索值:

 private Dictionary data = GetDataList(); string myString = (string)data[typeof(string)]; int myInt = (int)data[typeof(int)]; 

这将使获取值的过程略微更加健壮,因为它不依赖于以任何特定顺序出现的值。

将ArrayList转换为这样的字典的示例:

 ArrayList data = new ArrayList(); data.Add(1); data.Add("a string"); data.Add(DateTime.Now); Dictionary dataDictionary = new Dictionary(); for (int i = 0; i < data.Count; i++) { dataDictionary.Add(data[i].GetType(), data[i]); } 

我没有使用原始类型,而是有一个封装每种数据类型的抽象类。 然后,处理该类型的逻辑可以嵌入到类本身中。

 foreach( MyBaseData data in lstData ) { data.DoTheRightThing(); } 

一般来说,任何打开对象类型的代码都应该被认为是一种设计气味 – 它可能不一定是错的,但是再看看它可能是一个好主意。

虽然编写一个类来封装一个简单的类型可能会觉得不必要的工作,但我不认为我曾经后悔过这样做。

只是一些稍微清洁的代码:

 foreach (object obj in lstTop) { if(obj is string) {do this...) else if(obj is DateTime) {do this....} else if(obj is bool) {do this....} else if(obj is int) {do this....} } 

如果您的数组在同一位置始终具有相同的对象,则只需索引数组并执行直接转换。

  foreach (object obj in lstTop) { if(obj.GetType() == typeof(string)) {do this...) else if(obj.GetType() == typeof(DateTime)) {do this....} else if(obj.GetType() == typeof(bool)) {do this....} else if(obj.GetType() == typeof(int)) {do this....} } 

GetType方法返回对象的System.Type 。 因此,您需要将它与另一个使用typeof获得的System.Type进行比较。