【问题标题】:How to check the type of object in ArrayList如何检查 ArrayList 中的对象类型
【发布时间】:2011-01-27 14:27:01
【问题描述】:

有没有办法获取arraylist中对象的类型?

我需要如下(在 C# 中)制作一个 IF 语句:

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

谢谢

【问题讨论】:

    标签: c# object types arraylist


    【解决方案1】:

    使用GetType()了解Object的类型。

    【讨论】:

      【解决方案2】:

      你做的很好:

      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() 和 typeof()

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

        【讨论】:

          【解决方案4】:

          你就是这么干的:

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

          你可以为对象获取一个 Type 对象,但是你应该首先确保它不是空引用:

          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:是的,这是正确的。我写了这个例子来演示类型识别和转换,它在其他方面不是最优的。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-25
          相关资源
          最近更新 更多