c#中的反射是否提供了一种方法来确定某个给定的System。类型类型模型一些接口?

public interface IMyInterface {}

public class MyType : IMyInterface {}

// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);

当前回答

使用类型。IsAssignableFrom:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

其他回答

使用类型。IsAssignableFrom:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));
typeof(IMyInterface).IsAssignableFrom(someclass.GetType());

or

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

你有几个选择:

typeof (IMyInterface) .IsAssignableFrom (typeof (MyType)) typeof (MyType) .GetInterfaces () .Contains (typeof (IMyInterface)) 在c# 6中,你可以使用typeof(MyType).GetInterface(nameof(IMyInterface)) != null

对于通用接口来说,这有点不同。

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))

是什么

if(MyType as IMyInterface != null)

?

IsAssignableFrom现在移动到TypeInfo:

typeof(ISMSRequest).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());