【发布时间】:2011-01-27 14:27:01
【问题描述】:
有没有办法获取arraylist中对象的类型?
我需要如下(在 C# 中)制作一个 IF 语句:
if(object is int)
//code
else
//code
谢谢
【问题讨论】:
有没有办法获取arraylist中对象的类型?
我需要如下(在 C# 中)制作一个 IF 语句:
if(object is int)
//code
else
//code
谢谢
【问题讨论】:
使用GetType()了解Object的类型。
【讨论】:
你做的很好:
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() 和 typeof()
if( obj.GetType() == typeof(int) )
{
// int
}
【讨论】:
你就是这么干的:
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 更具体的类。
【讨论】: