在 C# 中如何在运行时检查对象是否属于特定类型?
最佳答案
您可以使用is 关键字。例如:
using System;
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}
static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
产生输出:
fred is not an integer
10 is an integer
关于c# - 在 C# 中,如何在运行时检查对象是否属于某种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3401447/