How to compare types
Quick question: how to compare a Type ty开发者_如何学Gope (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.
Any clue?
Try the following
typeField == typeof(string)
typeField == typeof(DateTime)
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.
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.
You can use for it the is
operator. You can then check if object is specific type by writing:
if (myObject is string)
{
DoSomething()
}
You can compare for exactly the same type using:
class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}
typeof returns the Type object from a given class.
But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.
class B : A {
}
var b = new B();
var typeOfb = b.GetType();
if (typeOfb == typeof(A)) { // false
}
if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}
If your instance is a Type
:
Type typeFiled;
if (typeField == typeof(string))
{
...
}
but if your instance is an object
and not a Type
use the as
operator:
object value;
string text = value as string;
if (text != null)
{
// value is a string and you can do your work here
}
this has the advantage to convert value
only once into the specified type.
http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx
Console.WriteLine("typeField is a {0}", typeField.GetType());
which would give you something like
typeField is a String
typeField is a DateTime
or
http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx
精彩评论