. NET face question 6

Source: Internet
Author: User

Common Interview Topics:

1. Do all types inherit System.Object?

2. Explain the differences between virtual, sealed, override, and abstract

3. What are the similarities and differences between interfaces and classes?

4. What is the difference between an abstract class and an interface? Is there anything you need to be aware of when you use it?

5. What is the difference between overloading and overwriting?

6. What are the similarities and differences between new and override in inheritance? Looking at the following code, there is a base class a,b1 and B2 that inherit from a, and change the behavior of the parent method print () in different ways. What does the test code output? Why?

public void Dotest () {    B1 B1 = new B1 (); B2 b2 = new B2 ();    B1. Print (); B2. Print ();      B1, B2    A ab1 = new B1 () should be output as expected; A ab2 = new B2 ();    Ab1. Print (); Ab2. Print ();   What should I export here? }public class a{public    virtual void Print () {Console.WriteLine ("A");}} public class b1:a{public    override void Print () {Console.WriteLine ("B1");}} public class b2:a{public    new void Print () {Console.WriteLine ("B2");}}

7. In the code below, the variables A and b are all int types, what is the code output?

int a = 123;int b = 20;var atype = A.gettype (); var btype = B.gettype (); Console.WriteLine (System.Object.Equals (Atype,btype)); Console.WriteLine (System.Object.ReferenceEquals (Atype,btype));

Where is the static field defined in 8.class stored in memory? Why would she say she won't be recycled by GC?

Type Basics Grooming Types type description

With the previous articles in this series, you have a basic understanding of value types and reference types, and their interrelationships. Such as. The main types in net are value types and reference types, and all types of base classes are, that is System.Object , all types of custom types that we provide with the FCL are ultimately derived from System.Object , so they also inherit the System.Object basic methods provided.

System.ObjectCan be said to be. NET in the source of all things, if not to be serious, it seems that only the interface does not inherit her. An interface is a special type that can be understood as an interface that is an ordinary type of constraint and specification that she cannot instantiate. (in the actual code, the interface can be expressed as object, just a syntax support, this view is not sure whether accurate, welcome to communicate)

In. NET code, we can easily create various types, a simple data model, a complex aggregation object type, or an abstraction of an objective world entity. Class is the most basic C # type (Note: The main discussion in this paper is the reference type, the type described in the article is not noted as a reference type), support inheritance and polymorphism. One of the C # class classes consists primarily of two basic members:

    • Status (Fields, constants, attributes, and so on)
    • Operations (methods, events, indexers, constructors, and so on)

You can easily create an instance of an object using the type created (or system-provided). Created with the new operator, which allocates memory for the newly instance, invokes the constructor to initialize the instance, and returns a reference to the instance, as in the following syntax:

< class name > < instance name > = new < class name > ([constructor parameters])

The created instance object is an object stored in memory (on the thread stack or on the managed heap), and what type of instance can be created in memory? She is the type object (Type objects).

Type objects (Type Object)

Take a look at the following code:

int a = 123;                                                           Create an instance of type int aint b =;                                                            Create an instance of type int Bvar atype = A.gettype ();                                               Gets the type of object instance a Typevar btype = B.gettype ();                                               Gets the type of object instance B typeconsole.writeline (System.Object.Equals (Atype,btype));                  Output: Trueconsole.writeline (System.Object.ReferenceEquals (Atype, btype)); Output: True

Any object has a GetType () method (provided by the base class, System.Object) that returns the type of an object that contains details about the interior of the object, such as fields, properties, methods, base classes, events, and so on, which can be obtained by reflection. In the above code, the type of two different int variables (int. GetType ()) is the same type, stating that int has a unique (quasi-static) Systen.int32 type in memory.

The type Object (Systen.int32) that is obtained above is an object that, like any other reference type, is a reference object that stores all the information of the Int32 type (all metadata information of the type).

About Type Type objects (object type):

> Each type (such as System.Int32) will have a unique type object in memory, which can be obtained by (int) A.gettype ().

The > object type is stored in an isolated area of memory called the load heap, which is created at the time of process creation and is not controlled by GC garbage collection, so the type object is not freed once created. His life cycle is created from the AppDomain to the end;

> said before, each reference object contains two additional members: Typehandle and synchronized index blocks, where typehandle points to the object's corresponding type object;

The loading of the > Type object is owned by class loader and is loaded before the first use;

Static fields in the > type are stored here (Type objects on the load heap), so static fields are global and not released;

You can refer to the diagram below, the first picture describes a relationship between objects in memory, the second picture is more complex, more accurate and comprehensive description of the structure of memory distribution.

Photo source

Method table

What is the main structure inside the type object? One of the most important is the method table, contains all the methods of the type inside the entrance, about the specific details and principles here do not repeat (too much, you can refer to the text at the end of the reference), this article is only a preliminary introduction, the main purpose is to solve the 6th question.

public class a{public    virtual void Print () {Console.WriteLine ("A");}} public class b1:a{public    override void Print () {Console.WriteLine ("B1");}} public class b2:a{public    new void Print () {Console.WriteLine ("B2");}}

The code for the 6th question, for example, defines two simple classes in the above code, a base class A,,b1 and B2 inherit from a, and then change the behavior of the parent class method in different ways. When the B1, B2 two variables are defined, the memory structure is as follows:

B1 B1 = new B1 (); B2 b2 = new B2 ();

Loading of method tables:

    • The method table is loaded when the parent class is in the former subclass, and the first load is a fixed 4 virtual method from System.Object: ToString, Equals, GetHashCode, and Finalize;
    • Then the virtual method of the parent class A is loaded;
    • Load your own method;
    • Finally, the constructor method: static constructor. cctor (), object constructor. ctor ();

Method entries in the Method table (method table slots) also have a lot of other information, such as the IL code that associates the method with the corresponding local machine code, and so on. In fact, the type object itself is also a reference type object, its internal also contains two attachment members: Synchronous index block and type object pointer Typehandel, specific details, the principle of interest can be in-depth understanding.

Method invocation: When executing code b1.Print() (where only the method invocation is concerned, ignoring the inheritance of the method), the corresponding type object is found through the Typehandel of the B1, then the method table slot is found, then the corresponding IL code, the first time the execution, The JIT compiler needs to compile the IL code into a local machine code, the machine code will be retained after the first execution, and the next execution will not need to be JIT-compiled. That's why it's said. NET program starts to warm up the reason.

. The nature of inheritance in net

The method table is created from the parent class to the subclass top-down, which is. NET is a good embodiment of inheritance, when found to overwrite the parent class virtual method overrides the same name of the parent method, all types of loading will be recursive to the System.Object class.

    • Inheritance is transitive, the subclass is an extension to the parent class, the parent class method must be inherited, and a new method can be added.
    • Subclasses can call the parent class methods and fields, and the parent class cannot call the subclass methods and fields.
    • Subclasses inherit not only the public members of the parent class, but also the private members, but are not directly accessible.
    • The New keyword interrupts the inheritance of a virtual method and breaks the inheritance pass of a virtual method.

Thus the type B1, B2 type Object further structure is as follows:

    • When loading an B1 type object, the override B1 is loaded. Print ("B1"), it is found that overwriting the override method, will overwrite the parent class with the same name virtual method print ("A"), is the following, simply means that in the B1 print only one implementation version;
    • When loading a B2 type object, the New keyword indicates that you want to hide the virtual method of the base class, at which point the print ("B2") in B2 is not a virtual method, and she is the new method in B2, which simply means that there are 2 implementations of print in the B2 type object;

B1 B1 = new B1 ();

B2 b2 = new B2 (); B1. Print (); B2. Print ();      

= new

B1 (); A ab2 = new B2 (); ab1. Print (); Ab2. Print ();   What should I export here?

What is the difference between the two lines of red highlighted in the code above, with the base class (A) and the B1 declaration itself? Similar to this code in the actual coding is very common, a simple summary:

    • No matter what makes a reference declaration, even if it is an object, there is no difference between the [= new type ()] on the right of the equal sign, and the B1 and AB1 objects are consistent in the memory structure, even if the object creation is not affected;
    • Their differences in the reference pointer type is different, this difference in the encoding of intelligent hints in the visual response, and in the actual method call is also directly related to the reference pointer type;
    • In general, different reference pointer types do not affect the creation of objects (new operations), but have an impact on the use of objects, such as method invocations, which is reflected in the execution results of the above code!

The IL code called above:

The invocation of the virtual method, in IL, is the use of instruction callvirt, the main meaning of which is that the specific method is dynamically determined at runtime:

callvirt uses virtual scheduling, which is the scheduling method based on the dynamic type of the reference type, and the callvirt instruction invokes the method based on the object type that the reference variable points to, dynamically binding at run time, primarily for calling virtual methods.

Different type pointers have different additional information in the virtual method table as flags to differentiate their access to the address area, called offset. Pointers of different types can only be executed within their specific address area. The compiler also has a principle when calling a method:

Execute the nearest principle: for the same name field or method, the compiler refers to it in its order, that is, to first access the field or method from which it was created.

Therefore, when executing the following code, offset of the reference pointer type points to the subclass, for example, according to the nearest lookup execution principle, normal output B1, B2

B1 B1 = new B1 ();

B2 b2 = new B2 (); B1. Print (); B2. Print ();      B1, B2 should be output as expected

And when the following code is executed, the reference pointer type is parent class A, and the reference pointer type offset points to the parent class, for example, according to the nearest lookup execution principle, output B1, A.

= new

B1 (); A ab2 = new B2 (); ab1. Print (); Cbp. Print ();   What should I export here?

. NET inheritance what is abstract class

Abstract classes provide multiple derived classes that share a common definition of a base class that can provide either an abstract method or a non-abstract method. Abstract classes cannot be instantiated, and they must be implemented by derived classes to implement their abstract methods, so the new keyword cannot be used for abstract classes and cannot be sealed.

Basic Features:

    • Abstract classes use an abstract declaration, and abstract methods are also marked with abstract;
    • Abstract classes cannot be instantiated;
    • Abstract methods must be defined in abstract classes;
    • Abstract classes can inherit an abstract class;
    • Abstract classes cannot be sealed (cannot use sealed);
    • Similar class, only support single inheritance;

A simple abstract class code:

Public abstract class abstractuser{public    int Age {get; set;}    public abstract void SetName (string name);}

The IL code is as follows, and both classes and methods use the abstract adornment:

What is an interface?

Interface simple understanding is a kind of specification, contract, so that the implementation of the interface class or structure in the form of consistency. The class or struct that implements the interface must implement all interface members in the interface definition and all interface members that the interface inherits from the other interfaces.

Basic Features:

    • The interface uses the interface declaration;
    • Interfaces are similar to abstract base classes, and interfaces cannot be instantiated directly;
    • The methods in an interface are abstract and cannot have implementation code, and any non-abstract type that implements an interface must implement all members of the interface:
    • Interface members are automatically exposed and cannot contain any access modifiers.
    • The interface itself can inherit from multiple interfaces, classes and structs can inherit multiple interfaces, but interfaces cannot inherit classes.

The following is a simple interface definition:

public interface iuser{    int: Age {get; set;}    void SetName (string name);}

Here is the IL code defined by the Iuser interface, which looks like the IL code of the abstract class Abstractuser above! Interfaces also use .Class ~ abstract tags, and method definitions work with tags in the same way as methods in an abstract class abstract virtual . It is therefore possible to think of an interface as a special abstract class that provides only definitions and no implementations.

Another small detail, said above that the interface is a special type, does not inherit System.Object , through the IL code can actually prove this point. Regardless of whether a custom type or abstract class is implicitly inherited System.Object , there is "extends [mscorlib]system.object" in the Il Code for Abstractuser, and the IL code for the interface does not have this piece of code.

About inheritance

About inheritance, too conceptual, it is not elaborate, mainly in the ordinary move the brick process more thinking, more summary, more experience. The main two ways of inheriting in. NET are class inheritance and interface inheritance, and the main ideas are different:

    • Class inheritance emphasizes a parent-child relationship, which is an "is a" relationship, and therefore can only be inherited (just like a person can have only one father);
    • Interface inheritance emphasizes a kind of specification, constraint, is a "CAN do" relationship, support multi-inheritance, is an important way to achieve polymorphism.

More precisely, classes can be called inheritance, and interfaces are called "implementations" more appropriately. More concepts and differences, you can look directly at the back of the answer, more or to understand.

Answer to the question: 1. Do all types inherit System.Object?

Basically yes, all value types and reference types inherit from System.Object, and the interface is a special type that does not inherit from System.Object.

2. Explain the differences between virtual, sealed, override, and abstract
    • Virtual declaration of the virtual method keyword, indicating that the method can be overridden
    • Sealed indicates that the class cannot be inherited
    • Override methods for overriding base classes
    • Abstract declares the keywords for abstract classes and abstract methods, which do not provide implementations, which are implemented by subclasses, and abstract classes cannot be instantiated.
3. What are the similarities and differences between interfaces and classes?

Different points:

1, the interface can not be directly instantiated.

2. The interface contains only the declaration of the method or property and does not contain the implementation of the method.

3, the interface can be multiple inheritance, the class can only single inheritance.

4, the class has the concept of partial class, the definition can be split between different source files, and the interface does not.

5, the meaning of the expression is different, the interface mainly defines a specification, the unified call method, that is, the specification class, the constraint class, the class is the method function realization and the collection

Same point:

1, interfaces, classes, and structs can inherit from multiple interfaces.

2. An interface is similar to an abstract base class: Any non-abstract type that inherits an interface must implement all members of the interface.

3. Interfaces and classes can contain events, indexers, methods, and properties.

4. What is the difference between an abstract class and an interface?

1. Inheritance: The interface supports multiple inheritance, and abstract classes cannot implement multiple inheritance.

2, the concept of expression: interface for the specification, more emphasis on the contract, abstract class for common, emphasizing father and son. Abstract class is a kind of high aggregation of things, then for the subclass of the inheritance abstract class, for the abstract class, belongs to the "is A" relationship, and the interface is to define the behavior specification, emphasizing the "Can do" relationship, so for the implementation of the interface subclass, relative to the interface, is "behavior needs to follow the interface to complete."

3, the method realization: to the abstract class method, namely can give the realization part, also may not give, but the interface method (abstract rule) cannot give the implementation part, the interface method cannot add the modifier.

4. Subclass rewrite: Inheriting classes are different implementations of the methods involved. The abstract method that the inheriting class defines for the abstract class can be used without rewriting, that is to say, the method of the abstract class can be used, and the method or property defined by the interface class must be overridden in the inheriting class, giving the corresponding method and property implementation.

5, the impact of the new method: in the abstract class, a new method, the inheritance class can not do any processing, and for the interface, you need to modify the inheritance class, provide a new definition of the method.

6. Interfaces can be used for value types (enumerations can implement interfaces) and reference types, and abstract classes can only be used for reference types.

7. Interfaces cannot contain fields and implemented methods, interfaces contain only methods, properties, indexers, and signatures of events; Abstract classes can define fields, properties, and methods that contain implementations.

5. What is the difference between overloading and overwriting?

Overloading: A method overload occurs when a class contains two methods with the same name but different signatures (the same method name, not the same argument list). Method overloads are used to provide methods that are semantically identical and functionally different.

Overwrite: Used in the inheritance of the class, the implementation of the virtual method of the parent class can be changed by covering the subclass method.

Main differences:

1, the method's coverage is the relationship between the subclass and the parent class, is the vertical relationship, the overloading of the method is the relationship between the methods in the same class, and is the horizontal relationship.
2. Overrides can only be made by one method, or only by a pair of methods; an overload of a method is a relationship between multiple methods.
3. The override requires the same parameter list, and the overload requires the parameter list to be different.
4, in the coverage relationship, call that method body, is based on the object type to determine, overload relationship, is based on the invocation of the actual parameter table and formal parameter list to select the method body.

6. What are the similarities and differences between new and override in inheritance? Looking at the following code, there is a base class a,b1 and B2 that inherit from a, and change the behavior of the parent method print () in different ways. What does the test code output? Why?
public void Dotest () {    B1 B1 = new B1 (); B2 b2 = new B2 ();    B1. Print (); B2. Print ();      B1, B2    A ab1 = new B1 () should be output as expected; A ab2 = new B2 ();    Ab1. Print (); Cbp. Print ();   What should I export here? Output B1, A}public class a{public    virtual void Print () {Console.WriteLine ("A");}} public class b1:a{public    override void Print () {Console.WriteLine ("B1");}} public class b2:a{public    new void Print () {Console.WriteLine ("B2");}}
7. In the code below, the variables A and b are all int types, what is the code output?
int a = 123;int b = 20;var atype = A.gettype (); var btype = B.gettype (); Console.WriteLine (System.Object.Equals (Atype,btype));          Output Trueconsole.writeline (System.Object.ReferenceEquals (Atype,btype)); Output true
Where is the static field defined in 8.class stored in memory? Why would she say she won't be recycled by GC?

Objects with type are stored on the loaded heap of memory, because the load heap is not managed by GC and its life cycle is not recycled by GC, as it does with the AppDomain.

All rights reserved, article source: http://www.cnblogs.com/anding

Personal ability is limited, the content of this article is only for study, discussion, welcome correction, Exchange.

. NET interview Analysis (00)-Opening to talk about the interview & Series Articles index

Resources:

Books: CLR via C #

Books: the. NET you must know

interface inherit to System.Object? : http://www.cnblogs.com/whitewolf/archive/2012/05/23/2514123.html

Some deep-seated discussions on CLR memory management [next]

[What you have to know about. NET] 15th: The essence of inheritance

Inside the. NET framework, see how the CLR creates a runtime object

. NET face question 6

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.