您的位置:首页 > 其它

类型是否实现了某个接口

2015-12-01 21:36 381 查看
定义下面的类和接口

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: