如何在C#中检查运行时对象是否属于某种类型?

时间:2010-08-03 23:17:36

标签: c# object types

如何在C#中检查对象在运行时是否属于某种类型?

9 个答案:

答案 0 :(得分:6)

您可以使用关键字。例如:

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

答案 1 :(得分:4)

MyType myObjectType = argument as MyType;

if(myObjectType != null)
{
   // this is the type
}
else
{
   // nope
}

包括空检查

编辑:错误纠正

答案 2 :(得分:2)

类型信息运算符(as,is,typeof): http://msdn.microsoft.com/en-us/library/6a71f45d(VS.71).aspx

Object.GetType()方法。

请记住,您可能必须处理继承层次结构。如果你有像obj.GetType()== typeof(MyClass)这样的检查,如果obj是从MyClass派生的东西,这可能会失败。

答案 3 :(得分:1)

myobject.GetType()

答案 4 :(得分:1)

obj.GetType()返回类型

答案 5 :(得分:1)

我无法添加评论,因此我必须将其添加为答案。请记住,从文档(http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.80%29.aspx):

  

如果是,表达式的计算结果为true   提供的表达式为非null,   并且可以将提供的对象强制转换为   提供的类型没有导致   抛出异常。

这与使用GetType检查类型不同。

答案 6 :(得分:1)

根据您的使用情况,'is'将无法按预期工作。从类Bar中获取一个Foo类。创建一个类型为Foo的对象obj。 'obj is Foo'和'obj is Bar'都将返回true。但是,如果使用GetType()并与typeof(Foo)和typeof(Bar)进行比较,结果将会有所不同。

解释是here,这是一段展示这种差异的源代码:

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);
      }
   }
}

答案 7 :(得分:0)

您还可以在c#7(pattern matching)中使用开关/案例

{{1}}

enter image description here

答案 8 :(得分:-1)

使用typeof关键字:

System.Type type = typeof(int);