C# 如何确定一个类型是否实现了特定的泛型接口类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/503263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:52:59  来源:igfitidea点击:

How to determine if a type implements a specific generic interface type

c#.netreflection

提问by sduplooy

Assume the following type definitions:

假设以下类型定义:

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

How do I find out whether the type Fooimplements the generic interface IBar<T>when only the mangled type is available?

当只有 mangled 类型可用时,如何确定该类型是否Foo实现了泛型接口IBar<T>

采纳答案by sduplooy

By using the answer from TcKs it can also be done with the following LINQ query:

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

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

回答by Andrew Hare

You have to check against a constructed type of the generic interface.

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

You will have to do something like this:

你将不得不做这样的事情:

foo is IBar<String>

because IBar<String>represents that constructed type. The reason you have to do this is because if Tis undefined in your check, the compiler doesn't know if you mean IBar<Int32>or IBar<SomethingElse>.

因为IBar<String>代表那个构造类型。您必须这样做的原因是因为 ifT在您的检查中未定义,编译器不知道您的意思是IBar<Int32>IBar<SomethingElse>

回答by Jon Skeet

You have to go up through the inheritance tree and find all the interfaces for each class in the tree, and compare typeof(IBar<>)with the result of calling Type.GetGenericTypeDefinitionifthe interface is generic. It's all a bit painful, certainly.

您必须通过继承树向上查找树中每个类的所有接口,如果接口是通用的,typeof(IBar<>)调用结果进行比较。当然,这一切都有些痛苦。Type.GetGenericTypeDefinition

See this answerand these onesfor more info and code.

有关更多信息和代码,请参阅此答案这些答案

回答by TcKs

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

回答by Pablo Retyk

First of all public class Foo : IFoo<T> {}does not compile because you need to specify a class instead of T, but assuming you do something like public class Foo : IFoo<SomeClass> {}

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

then if you do

那么如果你这样做

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

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

回答by GenericProgrammer

As a helper method extension

作为辅助方法扩展

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

Example usage:

用法示例:

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

回答by Ben Foster

I'm using a slightly simpler version of @GenericProgrammers extension method:

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

Usage:

用法:

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

回答by mindlace

There shouldn't be anything wrong the following:

以下应该没有任何问题:

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

For extra credit you could catch AmbiguousMatchException if you wanted to provide a specific generic-type-parameter with your IBar query.

如果您想在 IBar 查询中提供特定的泛型类型参数,您可以捕获 AmbiguousMatchException 以获得额外的积分。

回答by Sebastian Good

To tackle the type system completely, I think you need to handle recursion, e.g. IList<T>: ICollection<T>: IEnumerable<T>, without which you wouldn't know that IList<int>ultimately implements IEnumerable<>.

要彻底解决这个类型的系统,我想你需要处理递归,例如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));

    }

回答by Philip Pittle

In case you wanted an extension method that would support generic base types as well as interfaces, I've expanded sduplooy's answer:

如果您想要一个支持通用基类型和接口的扩展方法,我已经扩展了 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);
    }