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

后端 未结 8 1823
名媛妹妹
名媛妹妹 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条回答
  •  旧时难觅i
    2020-12-08 04:20

    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())
    

提交回复
热议问题