类型是否实现了某个接口

定义下面的类和接口

        interface Iccc
        {
            void dodo();
        }
        class ccc : Iccc
        {

            public void dodo()
            {
                
            }
        }
使用IsAssignableFrom方法, 确定指定类型的实例是否能分配给当前类型实例。IsAssignableFrom
public virtual bool IsAssignableFrom(
	Type c
)

如果满足下列任一条件,则为 true

  • c and the current instance represent the same type.

  • c is derived either directly or indirectly from the current instance.

  • The current instance is an interface that c implements.

  • c is a generic type parameter, and the current instance represents one of the constraints of c.

  • c represents a value type, and the current instance represents Nullable<c> (Nullable(Of c) in Visual Basic),e.g.typeof(int?).IsAssignableFrom(typeof(int).

            Type type=typeof(ccc);
            if (typeof(Iccc).IsAssignableFrom(type))
            {
                Console.WriteLine("true");
            }

结果打印为true

使用GetInterface方法

            if (type.GetInterface(typeof(Iccc).Name) != null)
            {
                Console.WriteLine("true");
            }

结果打印为true

i.e.IsAssignableFrom doesn't go through reflection like GetInterface, so it should be orders faster.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值