在C#中,我如何在运行时检查对象是否属于某种类型?
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
MyType myObjectType = argument as MyType;
if(myObjectType != null)
{
// this is the type
}
else
{
// nope
}
包含空值检查
编辑:更正错误
MyType myType = myObject as MyType;
,然后检查myType
是否为空;这并不意味着myObject
是一个MyType
,它只是可以分配给它。这是一个重要的区别。 - Matt Greerusing System;
namespace ConsoleApp {
public class Bar {
}
public class Foo : Bar {
}
class Program {
static void Main(string[] args) {
var obj = new Foo();
var isBoth = obj is Bar && obj is Foo;
var isNotBoth = obj.GetType().Equals(typeof(Bar)) && obj.GetType().Equals(typeof(Foo));
Console.Out.WriteLine("Using 'is': " + isBoth);
Console.Out.WriteLine("Using 'GetType()': " + isNotBoth);
}
}
}
myobject.GetType()
obj.GetType()
返回类型
object obj = null; obj.GetType();
,这会抛出一个NullReferenceException异常。 - Matt Greer我无法添加注释,所以只能把这个作为答案添加。请记住,根据文档(http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.80%29.aspx):
如果提供的表达式非空并且提供的对象可以强制转换为提供的类型而不会引发异常,则 is 表达式将求值为 true。
这与使用 GetType 进行类型检查不同。
在C# 7中,您还可以使用switch/case(模式匹配)。
string DoubleMe(Object o)
{
switch (o)
{
case String s:
return s + s;
case Int32 i:
return (i + i).ToString();
default:
return "type which cannot double.";
}
}
void Main()
{
var s= "Abc";
var i= 123;
var now = DateTime.Now;
DoubleMe(s).Dump();
DoubleMe(i).Dump();
DoubleMe(now).Dump();
}
is
通常意味着需要两个转换,而一个转换就足够了。这就是为什么它不经常被使用的原因。尽管如此,99.99% 的时间性能影响可能是无法察觉的。 - Matt Greeris'或
GetType()'可能是正确的解决方案。有关差异(包括代码)的详细信息,请参阅我的答案。 - Manfred