代码之家  ›  专栏  ›  技术社区  ›  Nick

从接口类型检测类

  •  -1
  • Nick  · 技术社区  · 17 年前

    public interface IFoo {}
    public class Bar : IFoo {}
    public class Baz : IFoo {}
    

    如果我得到了实现 IFoo ,如何确定该类型是否表示 Bar Baz (没有实际创建对象)?

    // Get all types in assembly.
    Type[]          theTypes = asm.GetTypes();
    
    // See if a type implement IFoo.
    for (int i = 0; i < theTypes.Length; i++)
    {
        Type    t = theTypes[i].GetInterface("IFoo");
        if (t != null)
        {
            // TODO: is t a Bar or a Baz?
        }
    }
    
    6 回复  |  直到 17 年前
        1
  •  4
  •   Darin Dimitrov    17 年前
    if (theTypes[i] == typeof(Bar))
    {
        // t is Bar
    } 
    else if (theTypes[i] == typeof(Baz))
    {
        // t is Baz
    }
    
        2
  •  3
  •   Marc Gravell    17 年前

    t 两者都不是 Bar 也没有 Baz -是的 IFoo . theTypes[i] 酒吧 巴兹 .

        3
  •  2
  •   Stan R.    17 年前

    当您执行GetInerface时,您只获得了接口。您需要做的只是获取实现该接口的类型,如下所示。

    var theTypes = asm.GetTypes().Where(
                                        x => x.GetInterface("IFoo") != null
                                        ); 
    

    现在,您可以循环使用它们并执行此操作。或者使用开关。

    foreach ( var item in theTypes )
      {
         if ( item == typeof(Bar) ) 
          {
             //its Bar
          }
         else if ( item == typeof(Baz) )
          {
            ///its Baz
          }
      }
    
        4
  •  1
  •   Vitaliy Ulantikov Peter Miehle    16 年前

    我认为这将有助于解决您的问题:

    IFoo obj = ...;
    Type someType = obj.GetType();
    if (typeof(Bar).IsAssignableFrom(someType))
        ...
    if (typeof(Baz).IsAssignableFrom(someType))
        ...
    
        5
  •  0
  •   leppie    17 年前

    我错过什么了吗?

    theTypes[i] 是那种类型。

        6
  •  0
  •   Sam Harwell    17 年前

    Type x = ...;
    bool implementsInterface = Array.IndexOf(x.GetInterfaces(), typeof(I)) >= 0;
    

    也就是说,我真的不知道你想要实现什么。