如何检查ArrayList中对象的类型

17

有没有一种方法可以获取ArrayList中对象的类型?

我需要按照以下方式(在C#中)进行if语句:

if(object is int)
 //code
else
 //code

谢谢

4个回答

33

你可以使用普通的GetType()和typeof()

if( obj.GetType() == typeof(int) )
{
    // int
}

16

你所做的是正确的:

static void Main(string[] args) {
    ArrayList list = new ArrayList();
    list.Add(1);
    list.Add("one");
    foreach (object obj in list) {
        if (obj is int) {
            Console.WriteLine((int)obj);
        } else {
            Console.WriteLine("not an int");
        }
    }
}
如果您想检查引用类型而不是值类型,可以使用 as 操作符,这样就不需要先检查类型再进行强制转换了:
    foreach (object obj in list) {
        string str = obj as string;
        if (str != null) {
            Console.WriteLine(str);
        } else {
            Console.WriteLine("not a string");
        }
    }

3

使用GetType()方法来获取Object的类型。


1

这就是你如何做到的方法:

if (theArrayList[index] is int) {
   // unbox the integer
   int x = (int)theArrayList[index];
} else {
   // something else
}

你可以为该对象获取一个 Type 对象,但是在此之前,你应该确保它不是一个 null 引用:

if (theArrayList[index] == null) {
  // null reference
} else {
  switch (theArrayList[index].GetType().Name) {
    case "Int32":
      int x = (int)theArrayList[index];
      break;
    case "Byte":
      byte y = (byte)theArrayList[index];
      break;
  }
}

请注意,除非您必须使用框架1.x,否则不应完全使用 ArrayList 类。相反,应该使用 List<T> 类,如果可能的话,应该使用比 Object 更具体的类。

最好只使用索引器从列表中提取值一次,然后将其转换为所需的类型。 - Andrew Bezzub
@Andrew:是的,没错。我写这个例子是为了演示类型识别和转换,其他方面并不是最优的。 - Guffa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接