[You must know. Net] 27th back: Does an interface actually inherit from an object?

Source: Internet
Author: User
Tags mscorlib

. Net website you must know|Anytao technology blog

[You must know. Net] 27th back: Does the interface actually inherit objects?

Released on: 2009.03.05:Anytao
2009Anytao.com, Anytao original works. Please refer to the author and source in the post.

Before
In. in the net world, we often hear nothing more than "system. object is the root of all types and the parent class of all types. in section 8.1 of "net: system. such title as object is system. object To the highest honor. Therefore, based on this point of view, we have the following sentence: "Does the interface inherit from system. Object ?", In fact, this is an episode discussed in the technical group today.

Www.anytao.com

 

1 origin

In. in the net world, we often hear nothing more than "system. object is the root of all types and the parent class of all types. in section 8.1 of "net: system. such title as object is system. object To the highest honor. Therefore, based on this point of view, we have the following sentence: "Does the interface inherit from system. Object ?", In fact, this is an episode discussed in the technical group today.

The assumption that "interface also inherits from object" is based on the following two points of view:

Viewpoint 1:

An interface is essentially a class, because the interface type is identified as. Class in Il after compilation. Since it is a class, it will inevitably inherit from system. object.

Opinion 2:

Suppose there are the following interfaces and types of Implemented interfaces:

 
// Release: code01, 2009/03/04 // Author: anytao, http://www.anytao.com // list: iobjectable. CSPublic interfaceIobjectable{}
// Release: code02, 2009/03/04 // Author: anytao, http://www.anytao.com // list: myobject. CSPublic classMyobject:Iobjectable{}
 
The following call is feasible for iobjectable objects:
// Release: code03, 2009/03/04 // Author: anytao, http://www.anytao.com // list: program. CSClassProgram{Static voidMain (String[] ARGs ){IobjectableOBJ =NewMyobject();// Call object instance methodsOBJ. tostring ();// Call object static methodsIobjectable. Equals (Null,Null);}}

Obviously, the iobjectable type variable OBJ can be accessed and stored in system. the instance methods tostring () and Virtual Methods equals in the object, of course, other public services are no exception: GetType (), equals (), gethashcode (), referenceequals (), it can also be inferred that the interface can access the object method.

It is undeniable that part of the above reasoning is completely correct, but unfortunately leads to the wrong answer, so in this article, I will clearly find out: the reason and principle that an interface does not inherit from an object. For an in-depth discussion of the essence of interfaces, see. net 1.5 "Fun interface" and 7.4 "abstract programming: interfaces and abstract classes.

2. search for answers from the object-oriented perspective

To find out the reason for interface inheritance, I want to start with the meaning of the interface, which is the best way to illustrate the problem? Interfaces, like the genie in object-oriented design, inject soul and vitality into oo ideas, and break through the vertical extension direction inherited by interfaces, give objects more flexible support mechanisms in a horizontal manner.

Interfaces encapsulate the abstraction of behaviors and define the contracts that must be observed by the implementer. For example. the icloneable interface type is assigned a contract such as "can be copied", implementing the system. collections. the type of the ienumerable interface is assigned a contract such as "enumeration". Different interfaces define different contracts, just as different laws constrain different behaviors. The contracts granted to interfaces should be kept relatively simple and uniform at least in the hierarchy. If GetType (), equals (), and gethashcode () are granted to all interfaces without exception () the referenceequals () and tostring () contracts make the purity and unification of interfaces impossible, for example, forcing any implementation of the system. the type of the icloneable interface is also an insult to icloneable.

Thinking from the single interface principle, an interface definition that contains a mix of things is clearly not the pure lineage that interfaces should have. For. Net designers who are familiar with the object orientation, this is a self-evident problem. Therefore, starting from the responsibility and meaning of the interface itself, it is completely correct to decide that the interface does not inherit from system. object.

3. Explore in Il

Once again, we used powerful il weapons to explore the truth. We opened all of them with reflector. net interfaces, such as ilist, iemumerable, and icollection, all share the same discovery that you cannot find the extends system. object:

 
.Class public interface AbstractAuto ANSI icloneable {. Custom instanceVoidSystem. runtime. interopservices. comvisibleattribute:. ctor (Bool) = {Bool(True)}. MethodPublicHidebysig newslotAbstract virtualInstanceObjectClone () cel managed {}}
 
The same is true for custom types. Let's look at the definition of iobjectable's il decompilation:
 
.Class public interface AbstractAuto ANSI iobjectable {}
 
While the inheritance relationship marked with extends is IlCodeTell us the best evidence of the truth.

Is system. Object really "?

Let's smile again and play with the object. Do all types have to inherit from the object? Actually not. When using ilasm.exe for IL code compilation, there is a parameter option noautoinherit, as described in its interpretation:

 
/Noautoinherit disable inheriting from system. objectDefault

Obviously, the noautoinherit option provides the "Remove hats" function for the. NET type. Simply put, when no base class is specified, the type cannot be automatically inherited from the object.

We can play a flip-and-pull ilgame to go through the anytao.insidenet.interfaceinside.exe console.ProgramUse the ildasm.exe tool dump as the Il code my. Il. For example, if myobject is decompiled:

. Class public auto ANSI beforefieldinit anytao. insidenet. interfaceinside. myobject extends [mscorlib] system. object implements anytao. insidenet. interfaceinside. iobjectable {. method public hidebysig specialname rtspecialname instance void. ctor () cel managed {// code size 7 (0x7 ). maxstack 8 il_0000: ldarg.0 il_0001: Call instance void [mscorlib] system. object ::. ctor () il_0006: Ret} // end of method myobject ::. ctor} // end of class anytao. insidenet. interfaceinside. myobject

We can select to delete all extendsinherited codes, compile noautoinherit with ilasm.exe, and generate

 
Ilasm/EXE/output: noobject.exe/noautoinherit my. Il

The newly-generated noobject.exe program will not inherit from the object. To some extent, it breaks the novelty of "returning all things". myobject is like a rootless tree that floats in some depth of my machine.

4 Conclusion

The interface does not inherit from the object. What should I do?ArticleAlthough it is short, take a sip of it and enjoy it.

So, how do we answer the two points that this article starts to question?

Answer Point 1:

An interface is essentially a class, but a special class has its own particularity in many aspects. For example, all methods and attributes are abstract and support multi-inheritance, since it is special, it is special. It is also one of them that does not inherit from any parent class.

Although this interpretation is far-fetched, it is the best explanation from the perspective of returning to the Interface source described above.

Answer question 2:

All. Net types are implicitly inherited from system. object, so for any interface type, for example:

 
// Release: code02, 2009/03/04 // Author: anytao, http://www.anytao.com // list: myobject. CSPublic classMyobject:Iobjectable{}

In essence, it is equivalent:

// Release: code02, 2009/03/04 // Author: anytao, http://www.anytao.com // list: myobject. CSPublic classMyobject:Object,Iobjectable{}

Therefore, for the myobject instance OBJ, the obj. tostring () is essentially that the myobject class inherits from the object, not that the iobjectable interface also inherits from the object. SoIobjectable. Equals () is the compiler.Iobjectable. Equals () is translatedObject. Equals ). In fact, for method calls of the interface declaration type, the implementation mechanism is completely different from the general direct method call and virtual method dispatch mechanism, we will discuss this important topic in detail later.

Okay, interface, it's not easy to love you, maybe we will meet again, so stay tuned to your friends: You must know. net.

 

Additional discussions:Leo ZhangDoes the interface inherit from objects? My views

 

Friendly support: Head, feilinsha, and Beijing club

Anytao | 2009 anytao.com

2009/03/05 | http://anytao.cnblogs.com/| http://www.cnblogs.com/anytao/archive/2009/03/05/must_net_27.html

This document is provided as "the status quo" without any guarantee and does not grant any rights. | This posting is provided "as is" with no warranties, and confers no rights.

The copyright of this article is owned by the author. You are welcome to repost this article, but you must keep this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be entitled to pursue legal liability.

References

    • What you must know. net 1.5 "Fun interface"
    • What you must know. Net 7.4 "abstract-Oriented Programming: interfaces and abstract classes"
    • Http://www.cnblogs.com/allenlooplee/archive/2007/01/22/627386.html

Learn more

[beneficial start]
[First: resentment: Is and as]
[second: Abstract programming: interface and abstract class]
[third: Historical entanglement: features and attributes]
[Fourth: Back-to-end: class and struct]
[Fifth: in-depth introduction to keywords --- New]
[Sixth: in-depth introduction to keywords --- base and this]
[seventh: taste type-starting from the general type system]
[eighth back: taste type-value type and reference type (on)-memory rational]
[ninth back: taste type-value type and reference type (medium)-unlimited rules]
[10: taste type-value type and reference type (lower) -application journey]
[11th back: Confused parameters --- art of transmission (top)]
[12th back: Confused parameters --- art of transmission (bottom)]
[13th back: Get to know Il from Hello, world]
[14th back: Get to know Il code --- get to know now]
[15th back: inheritance essence]
[16th back: simple keywords --- using full contact]
[17th back: appearance: overwrite and reload]
[18th back: object creation start and end (top)]
[19th back: Object creation start and end (bottom)]
[20th back: learning methodology]
[21st back: fully Understand null]
[22nd back: String resident (top) --- think with questions]
[23rd back: taste details, in-depth. net Type constructor]
[24th back: Understanding metadata and IL (upper)]
[25th back: Understanding metadata and IL (middle)]
[26th: Understanding metadata and IL (lower)]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.