开发者

How to check the type of object in ArrayList

开发者 https://www.devze.com 2022-12-23 02:36 出处:网络
Is there a way to get the type of object in the arraylist? I need to make an IF statment as the following (in C#):

Is there a way to get the type of object in the arraylist?

I need to make an IF statment as the following (in C#):

if(object is int)
 //开发者_开发技巧code
else
 //code

thanks


you can use the normal GetType() and typeof()

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


What you are doing is fine:

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

If you were checking for a reference type instead of a value type, you could use the as operator, so that you would not need to check the type first and then cast:

    foreach (object obj in list) {
        string str = obj as string;
        if (str != null) {
            Console.WriteLine(str);
        } else {
            Console.WriteLine("not a string");
        }
    }


Use GetType() to know the type of Object.


That's pretty much how you do it:

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

You can get a Type object for the object, but then you should make sure that it's not a null reference first:

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

Note that unless you are stuck with framework 1.x, you shouldn't use the ArrayList class at all. Use the List<T> class instead, where you should use a more specific class than Object if possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消