有没有一种方法可以获取ArrayList中对象的类型?
我需要按照以下方式(在C#中)进行if语句:
if(object is int)
//code
else
//code
谢谢
你可以使用普通的GetType()和typeof()
if( obj.GetType() == typeof(int) )
{
// int
}
你所做的是正确的:
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");
}
}
使用GetType()
方法来获取Object
的类型。
这就是你如何做到的方法:
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;
}
}
ArrayList
类。相反,应该使用 List<T>
类,如果可能的话,应该使用比 Object
更具体的类。