定义下面的类和接口
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.