简体   繁体   中英

In C#, how can I tell whether a generic type, T, is (not implements!) an interface?

Edit : I made a mistake an the premise was wrong. typeof(T).IsClass does indeed work - as does typeof(T)IsInterface, as was pointed out.

Say I have this method:

public T GetService<T>() where T : IService

I want to test whether the generic type, T, was sent into this method as an interface, rather than as a class. In other words, I want to differentiate between a call from MyClass.GetService<IService>() and MyClass.GetService<ImplementingClass>() . How can I do this?

I tried using is object , and is System.Object , but it will not make this distinction. Using typeof(T).IsClass and default(T).IsClass also don't work, because, respectively, the the System.Type return type is always a class, and because IsClass isn't available to a default T.

How else can I do this?

I think you can check runtime like below.

typeof(T).IsInterface

Please check this link for more details.

我测试了您的情况,typeof(T)。IsClass确实有效

It turns out my premise was wrong. This does indeed work:

typeof(T).IsClass

which returns false if an interface is specified.

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