Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to test if T inherits/implements a class/interface?

private void MyGenericClass<T> ()
{
    if(T ... inherits or implements some class/interface
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
673 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is a Method called Type.IsAssignableFrom().

To check if T inherits/implements Employee:

typeof(Employee).IsAssignableFrom(typeof(T));

If you are targeting .NET Core, the method has moved to TypeInfo:

typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T).Ge??tTypeInfo())

Note that if you want to constrain your type T to implement some interface or inherit from some class, you should go for @snajahi's answer, which uses compile-time checks for that and genereally resembles a better approach to this problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...