【问题标题】:Get inherited object type at runtime在运行时获取继承的对象类型
【发布时间】:2011-09-20 08:38:28
【问题描述】:

如果你考虑:

class A : IInterface { }

在运行时:

A instance = new A();

instance.GetType(); // returns "A"

IInterface instance = new A();

instance.GetType(); // returns "A"

object instance = new A();
instance.GetType(); // returns "A"

问题:如何获取IInterface作为类型?

【问题讨论】:

    标签: c# inheritance reflection interface types


    【解决方案1】:

    检查Type.GetInterface方法:

    您需要检查该对象是否实现了这样的接口,而不是尝试将其转换为某个接口对象。如果是这样,您可以将其转换为接口类型,或者,如果您希望将类型打印到某个流,如果它实现了接口,则打印它的字符串表示形式。

    您可以实现类似下一个的扩展方法以使生活更轻松:

    public static bool Implements<T>(this Type some)
    {
        return typeof(T).IsInterface && some.GetInterfaces().Count(someInterface => someInterface == typeof(T)) == 1;
    
    }
    

    最后,你可以这样做:

    Type interfaceType = someObject.GetType().Implements<IInterface>() ? typeof(IInterface) : default(Type);
    

    【讨论】:

    • 如果接口已知,则转换没有问题,但我正在根据运行时已知接口做一些事情,因此 GetInterfaces() 集合非常适合此。
    • 然后你可以按照扩展方法的方法。它会让你的代码比在你的解决方案中多次重复你封装的东西更干净:)
    【解决方案2】:

    如果您需要检查特定接口,可以使用“is”关键字 如果(实例是 IInterface) //做点什么

    【讨论】:

      【解决方案3】:

      GetType() 将始终为您提供您拥有实例的类的类型,无论您对它有什么样的引用。你在你的问题中观察到了这一点。

      如果您一直在寻找 IInterface 的类型对象,您也可以使用

      typeof(IInterface)
      

      如果需要类型实现的接口列表,可以使用

      instance.GetType().GetInterfaces()
      

      【讨论】:

        【解决方案4】:

        请参阅 Scott Hanselmans 关于该主题的相当不错的文章:

        http://www.hanselman.com/blog/DoesATypeImplementAnInterface.aspx

           Type type = instance.GetType()
           Type[] ifaces = type.GetInterfaces()
        

        应该可以解决你的问题。

        【讨论】:

          【解决方案5】:

          instance.GetType().GetInterfaces() 将获取实例类型(Type.GetInterfaces Method) 实现或继承的所有接口。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多