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

public interface IMyInterface {}

public class MyType : IMyInterface {}

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

当前回答

你有几个选择:

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<>))

其他回答

我刚刚做了:

public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}

我希望我能说在哪里I: interface,但interface不是一个通用参数约束选项。课堂离我们很近。

用法:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

我只是说工具,因为这更直观。我总是得到IsAssignableFrom flip-flopped。

如果你不需要使用反射,你有一个对象,你可以使用这个:

if(myObject is IMyInterface )
{
 // it's implementing IMyInterface
}

如果您有一个类型或实例,您可以很容易地检查它们是否支持特定的接口。

测试一个对象是否实现了某个接口:

if(myObject is IMyInterface) {
  // object myObject implements IMyInterface
}

测试一个类型是否实现了某个接口:

if(typeof(IMyInterface).IsAssignableFrom(typeof(MyType))) {
  // type MyType implements IMyInterface
}

如果你有一个通用对象,想要进行强制转换,并检查你强制转换的接口是否实现,代码如下:

 var myCastedObject = myObject as IMyInterface;

    if(myCastedObject != null) {
      // object myObject implements IMyInterface
    }

使用类型。IsAssignableTo(自。net 5.0起):

typeof(MyType).IsAssignableTo(typeof(IMyInterface));

正如在一些评论中所述,IsAssignableFrom可能被认为是“向后”的混淆。

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

or

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