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

8
在C#中,我如何在运行时检查对象是否属于某种类型?
9个回答

9
您可以使用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

3
我发现 is 这个关键字被使用得太少了,它使代码更易读! - Russell
2
使用 is 通常意味着需要两个转换,而一个转换就足够了。这就是为什么它不经常被使用的原因。尽管如此,99.99% 的时间性能影响可能是无法察觉的。 - Matt Greer
根据需求,is'或GetType()'可能是正确的解决方案。有关差异(包括代码)的详细信息,请参阅我的答案。 - Manfred

4
MyType myObjectType = argument as MyType;

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

包含空值检查

编辑:更正错误


你需要将转换的结果存储在某个变量中。MyType myType = myObject as MyType;,然后检查myType是否为空;这并不意味着myObject是一个MyType,它只是可以分配给它。这是一个重要的区别。 - Matt Greer

2
类型信息运算符(as, is, typeof): http://msdn.microsoft.com/en-us/library/6a71f45d(VS.71).aspx Object.GetType() 方法。
请记住,您可能需要处理继承层次结构。如果您有一个检查,例如 obj.GetType() == typeof(MyClass),则当 obj 是从 MyClass 派生的东西时,此检查可能会失败。

1
根据你的使用情况,'is' 可能无法按预期工作。以从类 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);
      }
   }
}

1
myobject.GetType()

1

obj.GetType() 返回类型


在过去的十年中,我不确定是否曾经看到过没有类型的.NET对象... - 所以在这种情况下,为了提高效率,我将省略对空值的检查。 - Manfred
4
他的意思是:object obj = null; obj.GetType();,这会抛出一个NullReferenceException异常。 - Matt Greer

1

我无法添加注释,所以只能把这个作为答案添加。请记住,根据文档(http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.80%29.aspx):

如果提供的表达式非空并且提供的对象可以强制转换为提供的类型而不会引发异常,则 is 表达式将求值为 true。

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


0

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

enter image description here


-2

使用typeof关键字:

System.Type type = typeof(int);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接