【问题标题】:How to determine if a type implements a specific generic interface type如何确定一个类型是否实现了特定的泛型接口类型
【发布时间】:2010-10-04 22:24:09
【问题描述】:

假设以下类型定义:

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

当只有 mangled 类型可用时,如何确定类型 Foo 是否实现了泛型接口 IBar&lt;T&gt;

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

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

    你必须这样做:

    foo is IBar<String>
    

    因为IBar&lt;String&gt; 代表构造类型。您必须这样做的原因是,如果 T 在您的检查中未定义,编译器将不知道您的意思是 IBar&lt;Int32&gt; 还是 IBar&lt;SomethingElse&gt;

    【讨论】:

      【解决方案2】:

      你必须向上遍历继承树并找到树中每个类的所有接口,并将typeof(IBar&lt;&gt;)与调用Type.GetGenericTypeDefinition的结果进行比较如果接口是通用的。当然,这有点痛苦。

      有关更多信息和代码,请参阅 this answerthese ones

      【讨论】:

      • 为什么不直接转换为 IBar 并检查是否为空? (我的意思是用'as'当然)
      • T 未知,无法转换为特定类型。
      • @sduplooy:也许我遗漏了一些东西,怎么可能不知道?它会编译公共类 Foo : IFoo {}
      【解决方案3】:
      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;
          }
      }
      

      【讨论】:

      • 由于 typeof(Foo) 返回一个 System.Type 对象(描述 Foo),GetType() 调用将始终返回 System.Type 的类型。您应该更改为 typeof(Foo).GetInterfaces()
      【解决方案4】:

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

      如果你这样做了

      Foo f = new Foo();
      IBar<SomeClass> b = f as IBar<SomeClass>;
      
      if(b != null)  //derives from IBar<>
          Blabla();
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 这是一个非常优雅的解决方案!我在 SO 上看到的其他人使用 foreach 循环或更长的 LINQ 查询。请记住,要使用它,您需要拥有 .NET 框架 3.5。
        • 我建议你把它作为一个扩展方法,就像 bit.ly/ccza8B 一样——会很好地清理它!
        • 根据您的需要,您可能会发现需要对返回的接口进行递归。
        • 我想说这应该在 .net 中更好地实现......作为核心......就像 member.Implements(IBar) 或 CustomType.Implements(IBar),甚至更好,使用关键字“is” ....我正在探索 c#,我现在对 .net 有点失望 ...
        • 小补充:如果 IBar 有多个泛型类型,你需要这样表示:typeof(IBar&lt;,,,&gt;) 用逗号充当占位符
        【解决方案6】:

        作为辅助方法扩展

        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!
        

        【讨论】:

        • "IsAssignableFrom" 正是我想要的 - 谢谢
        • 这不适用于提问者不知道泛型类型参数的要求。从您的示例 testObject.GetType().Implements(typeof(IDictionary));将返回 false。
        • @ctusch 那么,有什么解决方案吗?
        【解决方案7】:

        我正在使用@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();
        

        【讨论】:

        • 它仍然不能按照原始问题对通用接口的要求工作。
        【解决方案8】:

        以下应该没有错:

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

        如果您想为您的 IBar 查询提供特定的泛型类型参数,您可以捕获 AmbiguousMatchException。

        【讨论】:

        • 好吧,通常最好尽可能避免使用字符串文字。这种方法会使重构应用程序变得更加困难,因为重命名 IBar 接口不会更改字符串文字,并且只能在运行时检测到错误。
        • 尽管我通常同意上面关于使用“魔术字符串”等的评论,但这仍然是我找到的最佳方法。非常接近 - 测试 PropertyType.Name 等于“IWhatever`1”。
        • 为什么不这样呢? bool implementsGeneric = (anObject.Implements(typeof(IBar&lt;&gt;).Name) != null);
        【解决方案9】:

        要完全处理类型系统,我认为您需要处理递归,例如IList&lt;T&gt;ICollection&lt;T&gt;IEnumerable&lt;T&gt;,没有它你不会知道IList&lt;int&gt;最终实现了IEnumerable&lt;&gt;

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

        【讨论】:

          【解决方案10】:

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

          【讨论】:

            【解决方案11】:

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

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

            【讨论】:

              【解决方案12】:

              试试下面的扩展。

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

              【讨论】:

                猜你喜欢
                • 2011-08-23
                • 2012-09-13
                • 2010-11-10
                • 2013-02-14
                • 1970-01-01
                • 1970-01-01
                • 2012-06-09
                • 2011-02-01
                相关资源
                最近更新 更多