检查'T'是否继承或实现类/接口 [英] Check if 'T' inherits or implements a class/interface

查看:92
本文介绍了检查'T'是否继承或实现类/接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以测试T是否继承/实现了一个类/接口?

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
}


推荐答案

有一个名为 Type.IsAssignableFrom()

检查 T 继承/实现 Employee

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

如果您的目标是.NET Core,则该方法已移至TypeInfo:

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

typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T).Ge‌​tTypeInfo())

这篇关于检查'T'是否继承或实现类/接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆