[英]How can I check if an object is of a certain type at runtime in C#?
如何在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
MyType myObjectType = argument as MyType;
if(myObjectType != null)
{
// this is the type
}
else
{
// nope
}
包括空检查
编辑:错误纠正
类型信息运算符(as,is,typeof): http : //msdn.microsoft.com/en-us/library/6a71f45d (VS.71) .aspx
Object.GetType()方法。
请记住,您可能必须处理继承层次结构。 如果你有像obj.GetType()== typeof(MyClass)这样的检查,如果obj是从MyClass派生的东西,这可能会失败。
myobject.GetType()
obj.GetType()
返回类型
我无法添加评论,因此我必须将其添加为答案。 请记住,从文档( http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.80%29.aspx ):
如果提供的表达式为非null,则is表达式求值为true,并且可以将提供的对象强制转换为提供的类型,而不会引发异常。
这与使用GetType检查类型不同。
根据您的使用情况,“是”将无法按预期工作。 从类Bar中获取一个Foo类。 创建一个类型为Foo的对象obj。 'obj is Foo'和'obj is Bar'都将返回true。 但是,如果使用GetType()并与typeof(Foo)和typeof(Bar)进行比较,结果将会有所不同。
【解说】 这里 ,这里是一段源代码演示这种差异:
using 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);
}
}
}
你也可以在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();
}
使用typeof关键字:
System.Type type = typeof(int);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.