如何比较类型


130

快速问题:如何在C#中将类型类型(非双关语)与另一个类型进行比较?我的意思是,我有一个Type typeField,我想知道是不是System.StringSystem.DateTime等等,但typeField.Equals(System.String)不起作用。

有什么线索吗?

Answers:


179

尝试以下

typeField == typeof(string)
typeField == typeof(DateTime)

typeofC#中的运算符将为您提供Type命名类型的对象。 Type实例可与==运算符进行比较,因此这是一个比较实例的好方法。

注意:如果我没记错的话,在某些情况下,当涉及的类型是嵌入到程序集中(通过NoPIA)的COM接口时,这种情况就会崩溃。听起来好像不是这种情况。



32

您可以使用以下命令比较完全相同的类型:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof从给定的类返回Type对象。

但是,如果您具有从A继承的类型B,则此比较是错误的。您正在寻找IsAssignableFrom

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

7

如果您的实例是Type

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

但是,如果您的实例是an object而不是Typeuse as运算符:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

这具有value只转换一次到指定类型的优点。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.