简体   繁体   中英

In C# what is the equivalent of “is” keyword but using Type objects

An easy question I guess, but in the documentation of the Type class they only talk of interfaces on the GetInterfaces method.

ie typeof(ChildClass).XXX(typeof(ParentClass)

It depends on what you need; IsAssignableFrom, perhaps:

bool stringIsObj = typeof(object).IsAssignableFrom(typeof(string));

or IsSubclassOf :

bool stringIsObj = typeof(string).IsSubclassOf(typeof(object));

typeof运算(父类).IsAssignableFrom(typeof运算(ChildClass))

I suggest you search for an equivalent. Instead of using the "is" keyword like this:

if (object is class)
{ ... }

you could simply compare the types of those two like this:

if( typeof(object) == typeof(class)
{ ... }

BUT: this is not the same, the "is" keyword can determine if the object-class is of the specified class, an inheritence of that class, implements the interface, etc, whereas the typeof() equivalence just compares the actual type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM