【问题标题】:Detect Class from Interface Type从接口类型检测类
【发布时间】:2009-07-14 21:26:55
【问题描述】:

我有一个接口,以及一些继承自它的类。

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

【问题讨论】:

    标签: c# reflection interface


    【解决方案1】:
    if (theTypes[i] == typeof(Bar))
    {
        // t is Bar
    } 
    else if (theTypes[i] == typeof(Baz))
    {
        // t is Baz
    }
    

    【讨论】:

      【解决方案2】:

      t 既不是Bar 也不是Baz - 它是IFootheTypes[i]BarBaz

      【讨论】:

      • 好的,所以我使用 IsSubclassOf 测试了 theTypes[i]...这是正确的比较方法吗?普通的== 似乎不起作用。
      【解决方案3】:

      当您执行 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】:

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

        IFoo obj = ...;
        Type someType = obj.GetType();
        if (typeof(Bar).IsAssignableFrom(someType))
            ...
        if (typeof(Baz).IsAssignableFrom(someType))
            ...
        

        【讨论】:

          【解决方案5】:

          我错过了什么吗?

          theTypes[i] 是类型。

          【讨论】:

            【解决方案6】:

            支持分析/重构的“Type X 是否实现接口 I”的强类型解决方案是:

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

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

            【讨论】:

            • 它更像是“把所有实现接口I的东西都按照类型放在列表中”。最初的实现实际上是构造了每一个对象,这显然是浪费内存并且速度很慢。我只是存储类型而不是按需构建对象。
            • 一个更快的方法是 bool implementsInterface = typeof(IFoo).IsAssignableFrom(x);
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-30
            • 2019-06-27
            • 2023-03-22
            • 1970-01-01
            • 2019-06-25
            相关资源
            最近更新 更多