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

时间:2009-07-10 15:48:07

标签: c# .net .net-2.0

我有一个arylylist,其中包含不同类型的值,第一个值 - > 字符串,第二个值 - > 日期时间,第3个值 - > 布尔,第四个值是 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);

7 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:2)

.Net 2.0中的ArrayLists几乎总是错误的做法。即使你不知道列表会包含什么,你最好还是使用通用List<Object>,因为它可以与其他人通信,列表确实可以包含任何内容,而不仅仅是.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);

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

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

private Dictionary<Type, Object> 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<Type, Object> dataDictionary = new Dictionary<Type, object>();
for (int i = 0; i < data.Count; i++)
{
    dataDictionary.Add(data[i].GetType(), data[i]);
}

答案 4 :(得分:1)

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

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

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

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

答案 5 :(得分:0)

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

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....}
        }

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

答案 6 :(得分:0)

        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。因此,您需要将其与使用System.Type获得的另一个typeof进行比较。