假设有以下类型定义:

public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}

我如何找出类型Foo是否实现了通用接口IBar<T>时,只有manged类型是可用的?


当前回答

我使用一个稍微简单的版本的@GenericProgrammers扩展方法:

public static bool Implements<TInterface>(this Type type) where TInterface : class {
    var interfaceType = typeof(TInterface);

    if (!interfaceType.IsInterface)
        throw new InvalidOperationException("Only interfaces can be implemented.");

    return (interfaceType.IsAssignableFrom(type));
}

用法:

    if (!featureType.Implements<IFeature>())
        throw new InvalidCastException();

其他回答

public interface IFoo<T> : IBar<T> {}
public class Foo : IFoo<Foo> {}

var implementedInterfaces = typeof( Foo ).GetInterfaces();
foreach( var interfaceType in implementedInterfaces ) {
    if ( false == interfaceType.IsGeneric ) { continue; }
    var genericType = interfaceType.GetGenericTypeDefinition();
    if ( genericType == typeof( IFoo<> ) ) {
        // do something !
        break;
    }
}

方法检查类型是否继承或实现泛型类型:

   public static bool IsTheGenericType(this Type candidateType, Type genericType)
    {
        return
            candidateType != null && genericType != null &&
            (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == genericType ||
             candidateType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == genericType) ||
             candidateType.BaseType != null && candidateType.BaseType.IsTheGenericType(genericType));
    }
var genericType = typeof(ITest<>);
Console.WriteLine(typeof(Test).GetInterfaces().Any(x => x.GetGenericTypeDefinition().Equals(genericType))); // prints: "True"

interface ITest<T> { };

class Test : ITest<string> { }

这对我很管用。

您必须遍历继承树并找到树中每个类的所有接口,并将typeof(IBar<>)与调用Type的结果进行比较。GetGenericTypeDefinition如果接口是泛型的。当然,这一切都有点痛苦。

更多信息和代码请参见这个答案和这些答案。

通过使用tck的答案,也可以用以下LINQ查询完成:

bool isBar = foo.GetType().GetInterfaces().Any(x =>
  x.IsGenericType &&
  x.GetGenericTypeDefinition() == typeof(IBar<>));