mou*_*iec 17 c# types arraylist object
有没有办法在arraylist中获得对象的类型?
我需要制作一个IF语句如下(在C#中):
if(object is int)
//code
else
//code
Run Code Online (Sandbox Code Playgroud)
谢谢
bal*_*dre 33
你可以使用普通的GetType()和typeof()
if( obj.GetType() == typeof(int) )
{
// int
}
Run Code Online (Sandbox Code Playgroud)
Pao*_*sco 15
你做的很好:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您正在检查引用类型而不是值类型,则可以使用as运算符,这样您就不需要先检查类型然后再转换:
foreach (object obj in list) {
string str = obj as string;
if (str != null) {
Console.WriteLine(str);
} else {
Console.WriteLine("not a string");
}
}
Run Code Online (Sandbox Code Playgroud)