简体   繁体   中英

Getting the type of a “Type” in C# reflection

This is harder to find in the docs than I imagined. Anyway, I have some instances of Type . How can I find out if they represent classes, methods, interfaces, etc?

class Bla { ... }
typeof(Bla).GetKindOrWhatever() // need to get something like "Class"

(I'm using Mono on Linux but that shouldn't affect the question, I'm making portable code)

Type.IsClass might help here. Also Type.IsInterface .

Check out... http://msdn.microsoft.com/en-us/library/system.type_members.aspx

There are quite a few "IsXxxx" properties on Type. Hopefully these will do what you want.

By the way, you should check out other questions on this subject on SO, including this one...

typeof(System.Enum).IsClass == false

... if the types you're going to be checking are enum types, as there are some strange (but predictable) results.

There are a slew of properties off the Type class.

typeof(Bla).IsClass
typeof(Bla).IsInterface

etc.

http://msdn.microsoft.com/en-us/library/system.type_properties.aspx

The Type class have some properties that are named IsXXX.
For example it has a IsEnum, IsClass, IsInterface.
If I understand correctly your question this is what you need

As others have mentioned, the Type class has various properties that you can use if you just need to know whether your type is a class, interface, delegate, etc.

If you have a Type object and you want to know if it is a specific type, then I recommend using the IsAssignableFrom method found on the Type class:

        Type objectType = obj.GetType();
        Type interfaceType = typeof(IExample);

        if (interfaceType.IsAssignableFrom(objectType))
        {
            //...
        }

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