如何比较类型 [英] How to compare types
问题描述
快速的问题:如何比较在C#中另一类型的Type型(双关语不打算)?
我的意思是,我有一个键入TYPEFIELD
,我想知道这是否是 System.String
,的System.DateTime
等,但 typeField.Equals(System.String)
不起作用。
Quick question: how to compare a Type type (pun not intended) with another type in C#?
I mean, I've a Type typeField
and I want to know if it is System.String
, System.DateTime
, etc., but typeField.Equals(System.String)
doesn't work.
任何线索?
推荐答案
请尝试以下
typeField == typeof(string)
typeField == typeof(DateTime)
在C#中的的typeof
运营商将会给你一个键入
对象的命名类型。 键入
实例与媲美==
运营商,所以这是比较它们的好方法。
The typeof
operator in C# will give you a Type
object for the named type. Type
instances are comparable with the ==
operator so this is a good method for comparing them.
请注意:如果我没有记错,也有一些情况下,这种分解时所涉及的类型是它们(通过无PIA)嵌入到程序集COM接口。听起来并不像这里这样的话。
Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.
这篇关于如何比较类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!