I want to compare the type of an object to a type to see if they are the same. I do not have the object, just the type of the object.
I can do type1 == type2
and get general equality
I can have a recursive loop where I repeat the above step for type1.BaseType
until the BaseType is null.
I can do type1.GetInterface( type2.FullName ) != null
to check if type2 is an interface of type1
If I put it all together, I get
if ( type2.IsInterface )
return开发者_开发问答 type1.GetInterface( type2.FullName ) != null;
while ( type1 != null ) {
if ( type1 == type2 )
return true;
type1 = type1.BaseType;
}
return false;
Is that all the is
keyword is. I cannot find the right keyword to plug into the Reflector search to find the function and a google search on "is" was not really helpful
is (§14.9.10 of the standard) generally uses isinst, but it doesn't need to if the compile-time type is compatible via certain conversions.
A equivalent (in reverse) with a Type object is IsAssignableFrom. All of these are true:
"foo" is String;
"foo" is object;
typeof(String).IsAssignableFrom("foo".GetType());
typeof(object).IsAssignableFrom("foo".GetType());
精彩评论