Read "You must know. Net" again, review the basics, and review the classic

Source: Internet
Author: User
Tags define abstract

Memory Allocation
:
The CLR manages three areas of memory:

Thread stack, used to allocate value-type instances. The stack is mainly managed by the operating system and is not controlled by the garbage collector. When the method of the value-type instance ends, its storage unit is automatically released. Stack execution efficiency is high, but the storage capacity is limited.

GC heap for allocating small object instances. If the instance size of the reference type object is less than 85000 bytes, the instance will be allocated to the GC stack. When memory is allocated or recycled, the Garbage Collector may compress the GC stack, for more information, see the following description.

LOH (large object heap) heap is used to allocate large object instances. If the instance size of the reference type object is no less than 850
00 bytes, the instance will be allocated to the LOH stack, and the LOH heap will not be compressed and will be recycled only when full GC is collected.

Stack memory allocation mechanism
:
Value types are generally created on the thread stack. However, not all value types are created on the thread stack. For example, when a field of the class is used, the value type as part of the Instance member is also created on the managed stack. When a packing occurs, the Value Type field is also copied to the managed stack.

The instance of the reference type is allocated to the hosting stack, while the thread stack is the place where the object lifecycle begins. For a 32-bit processor, after the application completes the process initialization, the CLR
A reserved address space will be allocated to the available address space of the process, which is a process (each process can use
4 GB) memory area on the available address space, but does not correspond to any physical memory, this address space is the managed heap.
The managed stack is divided into multiple regions based on different storage information.
The most important thing is GC heap and loader heap. GC heap is used to store object instances and is managed by GC. Loader
Heap is divided into high-frequency heap, low-frequency heap, and stub
Heap stores different information on different stacks. The most important information of Loader heap is the metadata-related information, that is, the type object.
The loader heap is represented as a method table, while the method table
It records the stored metadata information, such as the base type, static field, implemented interface, and all methods. Loader heap is not controlled by GC, and its lifecycle is from creation
Unmount the appdomain.

Before entering the actual memory allocation analysis, it is necessary to explain several basic concepts to better discuss them in the following analysis.
Typehandle, type handle, points to the method table of the corresponding instance. Each object is created with this additional member and occupies 4 bytes of memory space. We know that each type corresponds to a method table. When a method table is created for compilation, it mainly contains the feature information of the type, the number of Implemented interfaces, and the number of slots in the method table.

Syncblockindex is used for thread synchronization. Each object also contains this additional member when it is created. It points to a memory block called synchronization block for Object synchronization management, it also occupies 4 bytes of memory space.

Nextobjptr is a pointer maintained by the managed heap to identify the location of the next newly created object in the managed heap. During CLR initialization, nextobjptr is located at the base address of the managed heap.

Add a new instance object to the managed heap, but add a certain value to the nextobjptr pointer. The newly added object will be allocated to the memory space pointed to by the current nextobjptr. Therefore, in the managed stack, objects for continuous allocation must be continuous in the memory. This allocation mechanism is very efficient.

What is the difference between static field memory allocation and release?

Static fields are also stored in the method table, after the slot array of the method table
The lifecycle is from creation
Unmount the appdomain. Therefore, no matter how many objects are created for a type, there is only one static field in the memory. Static fields can only be initialized by static constructors.
Before any object is created, or before any static field or method is referenced. For the detailed execution sequence, see the relevant discussion.

Inheritance
Is a kind of relationship between classes and classes in object-oriented systems. The inherited class is called a subclass or a derived class, And the inherited class is called a parent class, a base class, or a superclass. Through inheritance, the subclass has the attributes and methods of the parent class. Meanwhile, the subclass can also create a new class level by adding new attributes and methods or modifying the attributes and methods of the parent class.
The Inheritance Mechanism reflects the reusability, scalability, and security of object-oriented technology. It provides the basic technical basis for Object-Oriented Software Development and modular software architecture.

Adapter mode is mainly used
Converts an interface of a class to another interface. Generally, when the original system is changed, the new requirements are changed.
Class to complete the expansion and transformation of the existing storage system. The adapter mode mainly includes the following implementation methods: Class Adapter
Mode. Introduce a new type to inherit the original type and implement the newly added interface method. The disadvantage is that the coupling is high and too many new types need to be introduced. Object Adapter
Mode. By means of aggregation rather than inheritance, the original system is extended, loosely coupled, and few new types are achieved.

Inheritance:
The sealed class cannot be inherited.
In the inheritance relationship, we pay more attention to their commonalities rather than characteristics, because commonalities are the basis of hierarchical reuse, and features are the basis of system expansion.
Implements single inheritance and multiple interfaces.
From a macro perspective, inheritance focuses more on commonality, while polymorphism focuses more on difference.
The hierarchy of inheritance should be controlled. Otherwise, maintenance of the relationship between types will consume more energy.
Object-oriented principle: multiple combinations, less inheritance, low coupling, and high cohesion.

Two principles of Object Inheritance in. Net:
1. Focus on the object principle: calling the subclass or parent class method depends on whether the created object is a subclass object or a parent class object, rather than its reference class.
Type. For example, when bird bird2 = new chicken (), we are concerned that the object it creates is chicken.
Type. Therefore, the subclass inherits the fields and methods of the parent class, or overwrites the Virtual Methods of the parent class without paying attention to bird2.
Whether the reference type of is bird. Different reference types determine different access permissions for different objects in the method table.
Based on the object-of-interest principle, what are the differences between the following two situations?
Bird bird2 = new chicken ();
Chicken chicken = new chicken ();
Root
According to the above analysis, the bird2 object and the chicken object are the same in the memory layout. The difference is that the reference pointer type is different: bird2 is bird.
Type pointer, while chicken is chicken
Type pointer. Taking method call as an example, different types of pointers have different additional information in the virtual method table as a flag to differentiate the accessed address areas.
Offset. Different types of pointers can only be executed in a specific address area. When the Child class overwrites the parent class, the consistency of the access address area is ensured, so that different types of access have different access permissions.
Limitation.

2. Execute the proximity principle: For fields or methods of the same name, the compiler searches for the reference in order, that is, first accesses the field or method closest to it, for example, in the previous example
Bird2 is of the bird type, so it will first access bird_type (note that the compiler will not rename it here for the sake of differentiation), if the type is set
Public, then the bird value is returned here. This is why fields must be arranged in order when the object is created, and the parent class must be compiled before the child class.

Encapsulation
:
In the three elements of object-oriented, encapsulation features provide a means for program design to achieve interaction between systems, modules and modules, and classes.
The encapsulation hides the specific implementation details inside the class, and provides a unified access interface for external operations on internal data members. The advantage of this implementation is that the UI is separated, and the programmer does not need to know the specific implementation of the class, but only needs to control it according to the interface protocol. At the same time, the encapsulation ensures the security and reliability of the members inside the class.

Field, attribute, Method

Generally, the core terms of system requirement description can be abstracted as classes, and the actions driven by these terms can be abstracted as methods accordingly. Of course, specific design ideas should be effectively filtered, stripped, and abstracted based on the overall architecture objectives based on specific requirements. It demonstrates the charm of OO wisdom and design patterns.

Field)
It is usually defined as private, indicating the status information of the class.
The first principle of encapsulation is to define a field as private.
The encapsulation principle tells us that it is best to provide the field information of the class to the outside of the class in private mode, rather than in public mode. Otherwise, improper operations will cause unnecessary errors, the State information of the object is damaged, and data security and reliability cannot be guaranteed.

Property)
It is usually defined as public, indicating the external member of the class.
If the field is set to private, it needs to be exposed through the attribute.
Editing
The execution logic of the interpreter is: If a property is found and the get or set attribute is implemented in the property, it is generated accordingly.
Get _ property name and SET _ property name methods. Therefore, we can say that the essence of an attribute is to separate get and set
The accessors implement external methods to control attributes. The read/write behavior of attributes is actually a call of corresponding methods, it implements the method in a simple form.
The read/write control of class status information is implemented through access to public attributes. The first advantage is that the access restriction on data security and the reliability of internal data are avoided; second, it avoids the variable chain reaction caused by class extension or modification.
There is also a property with parameters, called indexer in C #. For CLR, there is no difference that does not include parameters, it is only responsible for implementing the corresponding accessors as the corresponding method. The difference is that the parameter processing process is added to the parameter attributes.

Method)
Encapsulates the behavior of a class and provides external performance of the class. It is used to provide external interfaces with public methods to encapsulate internal details, so as to achieve interaction and response with the outside.
From the analysis of the above attributes, we can see that the read and write operations on the attributes are actually implemented through methods. Therefore, the external interaction method is usually implemented as public.

Polymorphism

Classification: Based on the implementation method, we can further divide it into basic class inheritance type polymorphism and interface Implementation type polymorphism.
Operating Mechanism: from the technical implementation point of view, it is the dynamic binding mechanism of. Net that achieves object-oriented polymorphism.
Dynamic
State binding, also known as late binding, is different from static binding. Static binding can determine the association during the compilation period, which is generally implemented by method overloading. dynamic binding is implemented by checking the virtual method table at runtime.
Determine the method of dynamic join overwriting, which is generally implemented by inheritance and virtual methods. Strictly speaking, there is no static binding in. net. All. net source files are first compiled as Il
Code and metadata. During method execution, the Il code is instantly converted to local CPU commands by the JIT compiler. JIT
When compilation occurs at runtime, there is no association established completely during the compilation period, and the concept of static binding cannot be discussed.
Meaning: Polymorphism provides differentiated processing methods for the same class of objects.
The effective encapsulation and Inheritance of changes and commonalities reflects the idea of "one interface and multiple methods" and makes the method abstraction mechanism possible. In. net, the method is non-virtual by default.
C # For example, you must explicitly use virtual or abstract
Mark as a virtual method or abstract method to override the parent class method in the subclass. There is a close relationship between polymorphism and inheritance, polymorphism and heavy load among the basic elements of object-oriented, as described above, the basis of polymorphism is to establish
Effective inheritance system, so inheritance and overloading are the basis for the implementation of polymorphism.

Interface

The so-called interface is a contract, which is used to define a rule for everyone to abide. Therefore, many interfaces in. net use
Name suffix, such as inullable, icloneable, ienumerable, icomparable
Can be empty, can be cloned, can be enumerated, can be compared, in fact, it is a kind of contract to abide by the meaning, only to achieve icloneable
Interface Type to allow its instance objects to be copied.

Interface-oriented programming means that to have a certain feature in a custom class, you must abide by this contract.
Interface idriveable
{
Void drive ();
}

Public class busdriver: idriveable
{
Public void drive ()
{
Console. writeline ("experienced drivers can drive buses. ");
}
}
For example, to use foreach statement iteration, the premise is that the operation type must implement the ienumerable interface, which is also a contract.
The implementation interface also means that the same method performs different behaviors on different objects.
Essence: Therefore, an interface can be essentially considered as a class that Defines abstract methods. This class only provides the definition of methods without implementation of methods, its functions are implemented by the interface implementation class.
In addition, according to the interface isolation principle, the interface should be implemented as multiple small interfaces with a single function, rather than large interfaces with multiple functions. Through different combinations of multiple interfaces, the client implements different interfaces as needed to avoid interface contamination.

The interface rules can be summarized as follows:
The interface isolation principle emphasizes that the interface should be implemented as a small interface with a single function, rather than a fat interface with multiple functions. Class dependencies should be built on the smallest interface.
The interface supports multi-inheritance, which can be applied to both the value type and the reference type.
Do not add new members for published interfaces. This means that you must modify all types that implement the interfaces again. In actual applications, this is often impossible.
The interface cannot be instantiated and has no constructor. The interface members are implicitly declared as public.
The interface can act on the Value Type and reference type, and supports multi-inheritance.

. NET development performance optimization terms:

1. Release of resources: We recommend that you use the dispose mode instead of the finalize mode.
2. Select the appropriate Garbage Collector: workstation GC and service GC.
3. Implement weak references to objects as appropriate.
Weak reference is an intermediate state of object reference. It implements a mechanism that allows an object to reclaim its memory through GC and be accessible by applications. In. net, the weakreference class is used to indicate weak references, and its target attribute is used to indicate the objects to be traced. The value is assigned to the variable to create a strong reference for the target object.
4. Use using as much as possible to clear resources.
5. We recommend that you use a generic set instead of a non-generic set.
6. It is best to specify the size of the Set object during initialization.
7. The performance of specific types of arrays is better than that of arraylist.
8. The string resident mechanism is a special design implemented by CLR for the string type.
The string type is undoubtedly the most frequently used and widely used primitive type in programming. Therefore, CLR implements a mechanism called string resident to improve the performance of the string type, so as to achieve the same
The string may share the memory space. At the same time, the string resident is at the process level. Garbage collection cannot release the string objects maintained by the CLR internal hash table. It is released only when the process ends. These mechanisms are string-type Performance Improvement
And memory optimization provide a good foundation.
9. reasonably use system. String and system. Text. stringbuilder.
10. Try to rewrite the tostring method in the subclass.
Tostring
The method is a public virtual method provided by system. Object. Any type of. Net can inherit system. object.
The implementation method provided by the type. The default value is the full path name of the returned type. Rewrite tostring in a custom class or structure
In addition to effectively controlling the output results, it can also reduce the occurrence of packing operations to a certain extent.
11. Select for and foreach.
We recommend that you select foreach to process the cyclic structure of the enumerated sets.
12. design the system with multi-threaded processing.
13. Throw as few exceptions as possible and prohibit Exception Handling in a loop.
14. When an exception is caught, specify the specific exception filter in the catch block as much as possible. Multiple catch blocks should ensure the order of exceptions from special to general.
15. Check type compatibility in IS/as mode.
It is recommended to use is to implement type determination and use as to implement secure type conversion.
16. The trade-off between const and static readonly.
Const
It is the compilation frequency, and readonly is the runtime frequency. Therefore, const is efficient and readonly is flexible. In practical applications, it is recommended to use static
Readonly is used to replace the const to solve the Assembly reference inconsistency caused by const, and it also brings more flexibility control.
17. Avoid improper packing and unpacking, and select an appropriate alternative solution.
18. Try to use a one-dimensional zero-base array.
19. CLR uses the special il Operation Command newarr for the one-dimensional zero-base array. when accessing the array, it does not need to subtract the offset from the index, and JIT only needs to perform a range check, greatly improves access performance
20. Use the fxcop tool to check your code.
Fxcop is a code analysis tool developed by Microsoft for. Net hosting environments.

New keywords

Used as an operator to create objects and call constructors. Used as a modifier to hide an inherited member from a base class member. As a constraint, it is used to restrict the types of parameters that may be used as type parameters in a generic declaration.
The definition in msdn is: the new constraint specifies that any type parameter in the generic class declaration must have a common non-parameter constructor. When a generic class creates a new instance of the type, this constraint is applied to the type parameter.

Base keyword
It is used to implement access to the public or protected members of the base class in the derived class, but only limited to constructors, instance methods, and instances.
In the Property accessors, the specific features summarized in msdn include:
Call methods that have been overwritten by other methods on the base class.
Specify the base class constructor to call when creating a derived class instance.
This keyword
It is used to reference the current instance of the class, and also includes inherited methods. This can usually be hidden. The main package of the summary function in msdn
Including:
Restrict hidden members with similar names
Passing objects as parameters to other methods
Declare Indexer

Class and struct

1. The class is a reference type that inherits from the system. Object Class; the struct is a value type that inherits from the system. valuetype class and therefore does not have polymorphism. However, note that system. valuetype is a reference type.
2. From the perspective of job ability, class is behavior, while struct is often used to store data.
3. The class supports inheritance and can inherit from the class and interface. The struct does not have inheritance, and the struct cannot inherit from the class or be the base class of the class. However, the struct supports interface inheritance.
4. A class can declare a constructor without parameters and a destructor. A struct can only declare a constructor with parameters, but cannot declare a constructor. Therefore, struct does not have a custom default no-argument constructor. The default no-argument constructor simply initializes all values to their 0 values.
5. during instantiation, the class should use the new keyword, while struct may not use the New Keyword. If the new keyword is not used to instantiate struct, all its fields will be in the unallocated state, until all fields are initialized, otherwise referencing unassigned fields will cause compilation errors.
6. A class can be an abstract class and can declare Abstract Functions. struct is an abstract class and cannot declare Abstract Functions.
7. Class
You can declare the protected member, Virtual Member, sealed member, and override member, while struct
No, but it is worth noting that struct can reload 3 of system. Object
Virtual methods, such as equals (), tostring (), and gethashtable ().
8. the object replication of the class can be divided into shortest copy and deep copy (this topic will be described in detail later in this series, this article is not described in detail), and must be completed through special methods; the objects created by struct are easy to copy and can be directly connected by equal signs.
9. The class instance is made up by the garbage collector to ensure that the memory is recycled. The struct variable is automatically released immediately after it is used.
10. When passed as a parameter, the class variable is passed by address, while the struct variable is passed by value.

Differences between interfaces and abstract classes:

1. The interface supports multi-inheritance. abstract classes cannot implement multi-inheritance.
2. The interface can only define abstract rules. abstract classes can either define rules or provide implemented members.
3. An interface is a set of behavioral norms. An abstract class is an incomplete class that focuses on the concept of a family.
4. interfaces can be used to support callback. abstract classes cannot implement callback because inheritance is not supported.
5. An interface only contains methods, attributes, indexers, and event signatures, but cannot define fields or methods that contain implementations. An abstract class can define fields, attributes, and methods that have implementations.
6. The interface can act on the Value Type and reference type. The abstract class can only act on the reference type. For example, struct can inherit interfaces rather than classes.

Applicable scenarios of interfaces and abstract classes:

1. abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
2 The interface focuses on the can-do relationship type, while the abstract class focuses on the relationship of the IS-A type;
3. Interface multi-definition object behavior; abstract class multi-definition object attributes;
4. Public, protected, internal, and private modifiers can be used for interface definition. But almost all interfaces are defined as public, so you don't have to say much about the reason.
5. The interface remains unchanged, which is an important factor to consider. Therefore, when an extension is added by an interface, a new interface should be added instead of an existing interface.
6. Use the. NET Framework as an example. idisposable, idisposable, icomparable, iequatable, and ienumerable all contain only one public method.
7. The upper-case letter I before the interface name is a convention, just as it starts with an underscore below the field name. Stick to these principles.
8. All methods in the interface are public by default.
9
If a version problem is expected, you can create an abstract class.
. For example, if you have created a dog, a chicken, and a duck, you should consider abstracting the animal to deal with future things. Forward Interface
Adding a new member will force you to modify all the derived classes and re-compile them. Therefore, it is best to use an abstract class to solve the version issue.
10 A non-abstract class derived from an abstract class must include all the inherited abstract methods and the actual implementation of the abstract accessors.
11 abstract classes cannot use the new keyword or be sealed because they cannot be instantiated.
12 static or virtual modifiers cannot be used in abstract method declarations.

System. Object

System. object is a base class of all types. Any type is directly or indirectly inherited from the system. Object Class. If no base class is specified, all types are inherited from system. object by default, which has the basic features of the object.
It mainly includes:
The GetType method is used to obtain the object type information.
Use equals, referenceequals, and = to determine objects.
The tostring method is used to obtain the object string information. By default, the full name of the object type is returned.
The memberwiseclone method is used to implement the shortest copy of an object instance.
Use the gethashcode method to obtain the hash code of the object value.
Use the Finalize method to clear resources during garbage collection.

Delegate, event, anonymous method, Lambda expression

The delegate is essentially a class that inherits from
System. multicastdelegate class. This class maintains a list of delegates with links. When calling multicast delegates, it is called in the order of delegation lists. Also includes
Constructor that accepts two parameters and three important methods: begininvoke, endinvoke, and invoke.
The constructor includes two parameters: the first parameter indicates an object reference, which points to the instance of the callback function currently called by the delegate, and the second parameter identifies the callback method. After all the instantiated objects are created, call the callback method through invoke. It can be seen that the invoke method is actually called.

The. NET event model is built on the delegate mechanism, and has a thorough understanding of the delegate to understand the analysis of events. It can be said that the event is the encapsulation of the Delegate. from the example of the Delegate, we can know that the delegate can be operated at Will on the client, which destroys the object-oriented encapsulation mechanism to a certain extent, therefore, the event encapsulates the delegate ..
Complete definition process:
Defines an internal event parameter type to store the status information transmitted to the event handler when an event is triggered. eventargs is the base class of the event data class.
Declaring event delegation mainly includes two parameters: one representing the event sender object and the other representing the event parameter class object. Define event members.
Defines the method for triggering a notification event. It is implemented as the protected virtual method to override this method in a derived class to reject event monitoring.
Defines a method to trigger an event. For example, when calculate is called, a new calculation occurs.

The anonymous method is put into the place where the delegate object is used in the inline way, instead of creating a delegate to associate the callback method, that is, the delegate calls the anonymous method, the method code is directly associated with the delegated instance, which is concise and intuitive in syntax.

Lambda expressions are the core concept of functional programming. Now C #3.0 introduces lambda expressions to implement more concise syntaxes, and provides a syntax basis for LINQ.

Summary:
The delegate implements an object-oriented, type-safe method callback mechanism.
Using delegate as the extension of the delegate type and eventhandle as the suffix of the event Delegate is a standard naming rule.
Generally, the return value of a multicast delegate is void. It is not recommended that a non-void type be returned in the multicast delegate.
Anonymous methods and lambda expressions provide more concise syntax expressions. These new features are implemented based on the compiler, and there is no essential change in Il.
The. NET event is an application of the observer mode in the delegate and is implemented based on the. NET specification, reflecting better coupling and flexibility.

Exceptions in. net

The understanding of exceptions often has more or less misunderstandings:
For example, an exception is a program error
The error message returned by the error code is sufficient. The more exceptions in the system, the more fault tolerance can be guaranteed. Try/catch blocks are used as much as possible to process program execution. Use. Net custom
Exception can capture all the exception information without the need to process blocks of specific exceptions. Use exception classes as method parameters or return values. Report a custom exception by overwriting the tostring Method
Exception information, which cannot be ignored because some sensitive information may be leaked.

An exception is a violation of the implicit hypothesis of the program interface.

From try/catch/finally: parsing exception mechanism: the try clause usually contains the Execution Code that may cause exceptions, while the try block is usually executed until an exception or successful execution.
Complete. A catch clause contains the response code when an exception occurs. Its execution rule is: a try clause can be associated with zero or multiple catch clauses. CLR searches in top-down order.
Catch Block. An expression contained in a catch clause. This expression is called an exception filter and is used to identify exceptions caused by a try block. If the filter identifies this exception,
Response Code. If the filter does not accept this exception, the CLR searches for a higher layer along the call stack until the identified filter is found. If not found, an unprocessed exception is thrown. Exception filter,
Used to indicate predictable and recoverable exception classes. All exception classes must be of the system. Exception type or its derived class. The system. excetpion type is all
The base class of the exception type.

This exception is thrown in the program. % E

[Author: Brian )]

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.