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

public interface IMyInterface {}

public class MyType : IMyInterface {}

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

当前回答

IsAssignableFrom现在移动到TypeInfo:

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

其他回答

是什么

if(MyType as IMyInterface != null)

?

使用类型。IsAssignableFrom:

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

正如其他人已经提到的: 本杰明13年4月10日22:21

这当然很容易让人不注意,并得到争论 IsAssignableFrom倒退。我现在用GetInterfaces:p -

好吧,另一种方法是创建一个简短的扩展方法,在某种程度上,满足“最常见”的思维方式(并且同意这是一个非常小的个人选择,使它稍微“更自然”基于个人的喜好):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }
}

为什么不更通用一点呢(好吧,不确定它是否真的那么有趣,好吧,我假设我只是传递另一个“语法”糖):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }

    public static bool IsAssignableTo<TAssignable>(this Type type)
    {
        return IsAssignableTo(type, typeof(TAssignable));
    }
}

我认为这样可能会更自然,但这只是我个人的观点:

var isTrue = michelleType.IsAssignableTo<IMaBelle>();

注意,如果你有一个通用接口IMyInterface<T>,那么这个将总是返回false:

  typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */

这也不管用:

  typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>))  /* ALWAYS FALSE */

然而,如果MyType实现了IMyInterface<MyType>,这将工作并返回true:

  typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))

但是,在运行时您可能不知道类型参数T。一个有点俗气的解决方案是:

  typeof(MyType).GetInterfaces()
                .Any(x=>x.Name == typeof(IMyInterface<>).Name)

杰夫的解决方案就没那么俗气了:

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

下面是Type上的一个扩展方法,适用于任何情况:

public static class TypeExtensions
{
    public static bool IsImplementing(this Type type, Type someInterface)
    {
        return type.GetInterfaces()
             .Any(i => i == someInterface 
                 || i.IsGenericType 
                    && i.GetGenericTypeDefinition() == someInterface);
    }
}

(请注意,上面使用的是linq,它可能比循环慢。)

你可以这样做:

   typeof(MyType).IsImplementing(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
    }