简体   繁体   中英

Get inherited object type at runtime

If you consider:

class A : IInterface { }

at runtime:

A instance = new A();

instance.GetType(); // returns "A"

or

IInterface instance = new A();

instance.GetType(); // returns "A"

or

object instance = new A();
instance.GetType(); // returns "A"

Question: How to get IInterface as Type ?

instance.GetType().GetInterfaces()将获取实例类型(Type.GetInterfaces方法)实现或继承的所有接口。

GetType() will always give you the type of the class you have an instance of, no matter what kind of reference you have to it. You've observed this in your question.

If you're always looking to get a type object for IInterface, you could also use

typeof(IInterface)

If you need a list of interfaces which the type implements, you can use

instance.GetType().GetInterfaces()

Check Type.GetInterface method:

Instead of trying to get a casted to some interface object, you need to check if the object implements such interface. If so, you can cast it to the interface type or, if you're looking to print the type to some stream, if it implements the interface, print the string representation of it.

You can implement an extension method like next one in order to make life easier:

public static bool Implements<T>(this Type some)
{
    return typeof(T).IsInterface && some.GetInterfaces().Count(someInterface => someInterface == typeof(T)) == 1;

}

And, finally, you can do that:

Type interfaceType = someObject.GetType().Implements<IInterface>() ? typeof(IInterface) : default(Type);

See Scott Hanselmans pretty good article on that topic:

http://www.hanselman.com/blog/DoesATypeImplementAnInterface.aspx

   Type type = instance.GetType()
   Type[] ifaces = type.GetInterfaces()

Should solve your problem.

如果您需要检查特定的接口,可以使用'is'关键字if(instance is IInterface)//做一些事情

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