如何确定类型是否实现特定的通用接口类型

时间:2009-02-02 13:50:40

标签: c# .net reflection

假设以下类型定义:

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

当只有受损的类型可用时,如何确定类型Foo是否实现了通用接口IBar<T>

12 个答案:

答案 0 :(得分:357)

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

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

答案 1 :(得分:31)

您必须通过继承树查找树中每个类的所有接口,并将typeof(IBar<>)与调用Type.GetGenericTypeDefinition 的结果进行比较,如果界面是通用的。当然,这有点痛苦。

有关详细信息和代码,请参阅this answerthese ones

答案 2 :(得分:22)

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;
    }
}

答案 3 :(得分:9)

作为辅助方法扩展

public static bool Implements<I>(this Type type, I @interface) where I : class
{
    if(((@interface as Type)==null) || !(@interface as Type).IsInterface)
        throw new ArgumentException("Only interfaces can be 'implemented'.");

    return (@interface as Type).IsAssignableFrom(type);
}

使用示例:

var testObject = new Dictionary<int, object>();
result = testObject.GetType().Implements(typeof(IDictionary<int, object>)); // true!

答案 4 :(得分:5)

我正在使用稍微简单的@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();

答案 5 :(得分:4)

您必须检查通用接口的构造类型。

你必须做这样的事情:

foo is IBar<String>

因为IBar<String>表示构造的类型。您必须这样做的原因是,如果您的检查中未定义T,则编译器不知道您的意思是IBar<Int32>还是IBar<SomethingElse>

答案 6 :(得分:3)

首先public class Foo : IFoo<T> {}无法编译,因为您需要指定一个类而不是T,但假设您执行的操作类似于public class Foo : IFoo<SomeClass> {}

然后,如果你这样做

Foo f = new Foo();
IBar<SomeClass> b = f as IBar<SomeClass>;

if(b != null)  //derives from IBar<>
    Blabla();

答案 7 :(得分:3)

要完全解决类型系统,我认为你需要处理递归,例如IList<T>ICollection<T>IEnumerable<T>,如果没有IList<int>,您将不知道IEnumerable<>最终会实现 /// <summary>Determines whether a type, like IList&lt;int&gt;, implements an open generic interface, like /// IEnumerable&lt;&gt;. Note that this only checks against *interfaces*.</summary> /// <param name="candidateType">The type to check.</param> /// <param name="openGenericInterfaceType">The open generic type which it may impelement</param> /// <returns>Whether the candidate type implements the open interface.</returns> public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType) { Contract.Requires(candidateType != null); Contract.Requires(openGenericInterfaceType != null); return candidateType.Equals(openGenericInterfaceType) || (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) || candidateType.GetInterfaces().Any(i => i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType)); }

{{1}}

答案 8 :(得分:1)

如果你想要一个支持通用基类型和接口的扩展方法,我扩展了sduplooy的答案:

    public static bool InheritsFrom(this Type t1, Type t2)
    {
        if (null == t1 || null == t2)
            return false;

        if (null != t1.BaseType &&
            t1.BaseType.IsGenericType &&
            t1.BaseType.GetGenericTypeDefinition() == t2)
        {
            return true;
        }

        if (InheritsFrom(t1.BaseType, t2))
            return true;

        return
            (t2.IsAssignableFrom(t1) && t1 != t2)
            ||
            t1.GetInterfaces().Any(x =>
              x.IsGenericType &&
              x.GetGenericTypeDefinition() == t2);
    }

答案 9 :(得分:1)

检查类型是继承还是实现泛型类型的方法:

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

答案 10 :(得分:0)

尝试以下扩展程序。

public static bool Implements(this Type @this, Type @interface)
{
    if (@this == null || @interface == null) return false;
    return @interface.GenericTypeArguments.Length>0
        ? @interface.IsAssignableFrom(@this)
        : @this.GetInterfaces().Any(c => c.Name == @interface.Name);
}

进行测试。创建

public interface IFoo { }
public interface IFoo<T> : IFoo { }
public interface IFoo<T, M> : IFoo<T> { }
public class Foo : IFoo { }
public class Foo<T> : IFoo { }
public class Foo<T, M> : IFoo<T> { }
public class FooInt : IFoo<int> { }
public class FooStringInt : IFoo<string, int> { }
public class Foo2 : Foo { }

和测试方法

public void Test()
{
    Console.WriteLine(typeof(Foo).Implements(typeof(IFoo)));
    Console.WriteLine(typeof(FooInt).Implements(typeof(IFoo)));
    Console.WriteLine(typeof(FooInt).Implements(typeof(IFoo<>)));
    Console.WriteLine(typeof(FooInt).Implements(typeof(IFoo<int>)));
    Console.WriteLine(typeof(FooInt).Implements(typeof(IFoo<string>)));
    Console.WriteLine(typeof(FooInt).Implements(typeof(IFoo<,>)));
    Console.WriteLine(typeof(FooStringInt).Implements(typeof(IFoo<,>)));
    Console.WriteLine(typeof(FooStringInt).Implements(typeof(IFoo<string,int>)));
    Console.WriteLine(typeof(Foo<int,string>).Implements(typeof(IFoo<string>)));
 }

答案 11 :(得分:-1)

以下应该没有任何错误:

bool implementsGeneric = (anObject.Implements("IBar`1") != null);

如果你想在IBar查询中提供一个特定的泛型类型参数,你可以获得额外的功劳。