Check if 'T' inherits or implements a class/interface

后端 未结 8 1811
名媛妹妹
名媛妹妹 2020-12-08 04:00

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

private void MyGenericClass ()
{
    if(T ... inherits or implements some class/i         


        
8条回答
  •  暖寄归人
    2020-12-08 04:07

    The correct syntax is

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

    Documentation

    Return Value: true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c, or if c represents a value type and the current Type represents Nullable (Nullable(Of c) in Visual Basic). false if none of these conditions are true, or if c is null.

    source

    Explanation

    If Employee IsAssignableFrom T then T inherits from Employee.

    The usage

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

    returns true only when either

    1. T and Employee represent the same type; or,
    2. Employee inherits from T.

    This may be intended usage in some case, but for the original question (and the more common usage), to determine when T inherits or implements some class/interface, use:

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

提交回复
热议问题