简体   繁体   English

接口的类层次结构C#

[英]Class Hierarchy for Interfaces C#

I'm playing around with some classes and interfaces, and have developed a simple method to determine the hierarchy of a class, ie to identify the chain of inheritance. 我正在玩一些类和接口,并开发了一种简单的方法来确定类的层次结构,即识别继承链。

public static void OutputClassHierarchy(Type ty)
{
    if (ty.BaseType == null)
    {
        Console.WriteLine("{0}: Base", ty);
        Console.WriteLine("");
        return;
    }
    Console.WriteLine("{0} : {1}", ty, ty.BaseType);
    OutputClasshierarchy(ty.BaseType);
}

So, for 因此对于

OutputClassHierarchy(typeof(System.Exception));

I get the output: 我得到输出:

System.Exception : System.Object System.Exception:System.Object

System.Object : Base System.Object:Base

Which is what I expect. 这是我的期望。

But, If I attempt the same with an Interface that implements another interface, ie 但是,如果我尝试使用实现另一个接口的接口,即

interface IMyInterface : IDisposable
{
    void Hello();
}

...

OutputClassHierarchy(typeof(IMyInterface));

I get the output: 我得到输出:

MyNameSpace.IMyInterface : Base MyNameSpace.IMyInterface:Base

So, what is going on here? 那么,这里发生了什么? Is it possible to infer the interface hierarchy as declared above, or is there no such thing when it comes to interfaces? 是否有可能推断出上面声明的接口层次结构,或者在接口方面没有这样的东西?

Also, where is System.Object in all of this? 另外,所有这些中的System.Object在哪里? I thought everything was built upon it. 我以为一切都建立在它之上。

Interfaces are not derived from Object, so it won't show up when you output the base of it. 接口不是从Object派生的,因此在输出它的基础时它不会显示。 Here is Eric Lippert's comment on things which derive from Object (and things which are convertable to type Object). 以下是Eric Lippert对从Object派生的东西(以及可转换为Object类型的东西)的评论。

http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx

This SO answer may help answer your question about interfaces containing other interfaces: 这个SO答案可能有助于回答有关包含其他接口的接口的问题:

How to get interface basetype via reflection? 如何通过反射获取接口基类型?

Interfaces contain other interfaces, they don't derive from them so it won't show up when looking for it's base type. 接口包含其他接口,它们不是从它们派生的,因此在查找它的基本类型时它不会显示。

An interface doesn't have a single base type, as it could implement several other interfaces, eg 接口没有单一的基本类型,因为它可以实现其他几个接口,例如

public IMyInterface : IDisposable, IComponent

However, you can get at those interfaces by using the GetInterfaces method: 但是,您可以使用GetInterfaces方法获取这些接口:

var interfaces = typeof(IMyInterface).GetInterfaces();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM