Jar*_*Par 168
请尝试以下方法
typeField == typeof(string)
typeField == typeof(DateTime)
Run Code Online (Sandbox Code Playgroud)
typeofC#中的运算符将为您提供Type指定类型的对象. Type实例与==运营商相当,因此这是比较它们的好方法.
注意:如果我没记错的话,有些情况下,当涉及的类型是嵌入到程序集中的COM接口时(通过NoPIA),这会破坏.这听起来不是这样的.
Raf*_*jer 64
您可以使用它作为is 操作员.然后,您可以通过写入来检查对象是否是特定类型:
if (myObject is string)
{
DoSomething()
}
Run Code Online (Sandbox Code Playgroud)
GvS*_*GvS 30
您可以使用以下方法比较完全相同的类型:
class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您的实例是Type:
Type typeFiled;
if (typeField == typeof(string))
{
...
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您的实例是object而不是Type使用as运算符:
object value;
string text = value as string;
if (text != null)
{
// value is a string and you can do your work here
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是value只能将一次转换为指定的类型。