1. system. Object
| Public instance method |
brief description |
| virtual bool equals (Object OBJ) |
check whether the two objects are equal. If they are equal, true is returned; otherwise, false is returned. |
| virtual int gethashcode () |
Returns a hash code of this object. If this object is used as a key value by a set, this value will take effect |
| type GetType () |
return the type of the current object. Type is represented by an instance object inherited from system. Type |
| virtual string tostring () |
Returns a string that represents the current object. In system. object, this method returns the complete name of the current object type |
Instance equals Method
Compare whether the current object and the parameter object are equal.
In system. object, this method is "reference comparison" to compare whether this reference and parameter reference Reference reference the same object. True or false
Assume that the two string variables A and B are assigned the same value, and the logic is the same, but the equals () rules are different. Therefore, you can override this method when designing a new category.
The implementation content is the same .. In. net, system. valuetype is used as the base class of all value types. Override this method to achieve content comparison.
Instance gethashcode Method
Returns a hash code of the current object. This method is called when the object is used as the key value of the set.
Three methods to test the gethashcodeAlgorithmCorrectness
1. If the two objects are equal (equals), the two objects call the gethashcode method and return the same value.
2. If the same object calls the gethashcode method in any situation, the returned value should return the same value
3. Different objects call the gethashcode method, and the returned values should be evenly distributed in the Integer Set.
GetType Method
Public method: GetType. Returns aObject Type.
SearchProgramSet metadata to find the definition of this type. The tostring method of system. Object uses the GetType method.
Public static method |
Brief Description |
| Bool equals (Object obja, object objb) |
Determines whether the two objects are equal. If the two objects are equal, true is returned; otherwise, false is returned. |
| Bool referenceequals (Object obja, object objb) |
Compare whether the references of two objects are equal. True is returned if they are equal. Otherwise, false is returned. |
Referenceequals Method
Compare two objects. If the references are equal, true is returned; otherwise, false is returned. Regardless of the value type, the returned result must be false.
Equals Method
Implementation is relatively simple, and content comparison is achieved by using the instance equals Method
Public static bool equals ( Object left, Object right) { // check whether the object is the same If (Left = right) return true ; If (Left = null ) | (Right = null ) return false ; return left. equals (right) ;}
Protected instance method |
Brief Description |
| Object memberwiseclone () |
Light ReplicationInstance of the current object and return the reference of the Copied object |
| Finalize |
. Net destructor |
Ii. Value Type and reference type
(1) Value Type
Inherited from system. valuetype
Common value types includeStructure, Enumeration, integer, floating point, Boolean, etc.
(2) Reference Type
All types defined by the class keyword are reference types.
(3) Differences
1) assign values to different time zones
A Value Type Variable directly obtains a real data copy.
The value assignment of the reference type is only because the reference of an object is assigned to a variable, which can lead to multiple variables referencing an actual object instance.
2) Differences in memory allocation
Objects of the value type are stored inStackAllocate memory on,
Objects of the reference type are stored inHeapAllocate memory on.
3) Differences in inheritance Structures
All value types are inherited from the system. valuetype object and allocated to the stack.
System. Object and all reference type objects are allocated to the heap.
Iii. packing and unpacking
Packing
System. object is the base class of all value types. All value types must be implicitly converted to system. Object type. When a conversion occurs, CLR needs to do additional work to move the value types on the stack to the stack. This operation is boxed.
Procedure
1. Allocate a memory space on the heap. The size is equalSize of value type objects to be packedAddMembers of both reference type objects: type objects
Pointer and synchronization block reference
2. Copy the value type object on the stack to the newly allocated object on the stack.
3. Return a reference pointing to the new object on the heap and store it in the Value Type of the boxed object on the stack.
These steps do not need to be compiled by the programmer. In the case of packing, the compiler automatically adds the intermediate execution of the above functions.Code.
Unpack
Unboxing: Copies the objects in the heap to the stack and returns the value.
In the process, The binning operation will determine whether the object type of The binning is consistent with the reference of the value type to be copied. inconsistency will throw an invalidcastexception
Impact: packing and unpacking means a series of operations on the heap and stack space. These operations have a high performance cost, especially when the speed is much slower than the stack, these operations may cause garbage collection.
Applicable scenarios:
1. Value Type formatted output (boxed)
The following code can be compiled and executed, but it will lead to an unnecessary packing operation
IntI = 10; console. writeline ("The I value is :"+ I );
After optimization, packing is not involved
IntI = 10;// Obtain a String object using the tostring method. The string is of the reference type.Console. writeline ("I value: o {0 }"+ I. tostring ());
2. system. Object-type container
A common container class, such as arraylist, is a system. object container. Any value type that is put into the arraylist object will cause a packing operation, and a unpacking operation will be triggered for corresponding removal.
Therefore, you should use the generic technology to avoid using the system. Object type container when you can determine the type.
III. C # whether global variables
C # does not have a traditional global variable. in C # programs, any object data must belong to a certain type.
PassPublicStaticTo implement all functions of the previous global variables. For example, the Asp.net program uses the application object and the configuration file to store configurable data.
4. Structure struct
It can be seen as a micro class. Supports private and public member variables
Supported attributes and Methods
Constructor is supported,You cannot customize the construction method without parameters., C # The Compiler adds a non-argument public structure to the structure
Function members in this method are automatically set to 0. You cannot set the initial value during definition.
Supports rewriting virtual methods defined in system. object.
Inheritance is not supported.
It is inherited from the system. valuetype class, so struct is a value type.
It is often used to store data sets, but the types that involve complex operations should be designed as classes rather than structures.
V. Type Initiators
1. Concept
In. net, each type has an initialized device. You can define the initialization tool by yourself, or use the default compiler to add the initialization tool.
The type of the initiator has the same name as the type defined with the static keyword, and there is no parameter, and no return value.
Different from constructors, the type initiator cannot be explicitly called, and each type can have only one type initiator. CLR guarantee
Before any static members of the class are used, the type of the initializer will be called. This concept is essentially no different from the initialization expression of static member variables.
Public classCctor{// Initialization expressionPublic static intM_int = 1;// InitiatorStaticCctor () {m_int = 2 ;}// ConstructorPublicCctor () {console. writeline ("Constructor call. ");}Static voidMain (String[] ARGs) {console. Read ();}}
C # during compilation, the compiler adds all the static member variable initialization expressions to the initializer, and adds them before the content of the custom initiator.
2. Call Policy
In the intermediate code, the initialization tool is named cctor (). Two call policies
1). When the type does not have the beforefieldinit metadata attribute, CLR will call the initializer before any member of the type is used.
2). When the type has the beforefieldinit metadata attribute, CLR can schedule the call of the initializer freely. You only need to ensure that any static member variables have been called before they are used.
Vi. method parameter transfer method
Keywords |
Brief Description |
| Ref |
Reference transfer parameters, which must be initialized before transmission |
| Out |
Reference transfer parameters, which must be initialized before return |
| Params |
You can specify the parameter method when the number of parameters is variable. |
1). Ref and out keywords
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text;Namespace Test { Class Useles { Static void Main ( String [] ARGs ){ Int I = 0; Console . Writeline ( "Original Value :" + I. tostring (); notref (I ); Console . Writeline ( "After the non-reference parameter passing method is called :" + I. tostring (); Ref (I ); Console . Writeline ("After you call the reference passing parameter method :" + I. tostring () J ); Console . Read ();} // Parameters are passed without the ref keyword Public static void Notref ( Int I) {I ++ ;} // Use the ref keyword to pass the Parameter Public static void Ref ( Int I) {I ++ ;}}}
Result 0, 0, 1
The notref method does not pass parameters in reference mode. Therefore, the method returns a copy of integer I. how to operate it is irrelevant to the original data.
2). Params
Params is a very useful keyword. It allows methods to determine the number of parameters when defining, similar to array parameters.
Disadvantage: After the Params parameter is declared in the method, no parameters can be added after it.
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text; Namespace Test { Class Useles { // Parameters are passed without the Params keyword Public static void Notparams ( Object [] Par ){ Foreach ( Object OBJ In PAR) Console . Writeline (OBJ );} // Use the Params keyword to pass Parameters Public static void Paramsparam ( Params Object [] Par ){ Foreach ( Object OBJ In PAR) Console . Writeline (OBJ );} // Test Static void Main ( String [] ARGs ){ String S = "I am a string" ; Int I = 10; Double F = 2.3; // The array object needs to be declared to pass in through it Object [] Par = New Object [3] {s, I, f}; notparams (PAR );// Params Keyword Method Paramsparam (S, I, F ); Console . Read ();}}}
VII. Access Level
Type access level
Name |
Keywords in C # |
Brief Introduction |
| Private |
Private |
Same typeAll methods orTypeEmbedded typeAll methods |
| Family |
Protected |
Same typeIn all the methods and typesEmbedded typeAll methods andDerived typeAll methods in are accessible |
| Assemly |
Internal |
Same AssemblyAll methods in are accessible |
| Family & assemly |
Not Implemented |
All methods that meet both the family and assemly Constraints |
| Assemly or family |
Protected internal |
All methods that meet assembly or family constraints |
| Public |
Public |
All methods are accessible. |
Access Level of type members
Type |
Default accessibility level in C # |
Configurable accessibility level |
| Enum |
Public |
Not configurable |
| Class |
Private |
Pubic Protected Internal Private Protected internal |
| Interface |
Public |
Not configurable |
| Struct |
Private |
Public Internal Private |
8. Deep replication and light Replication
Light Replication
When copying an object, copy allNon-staticValue Type MemberAnd allReference Type MemberOfReference.
Deep Replication
Do not copy allNon-staticValue Type MemberAnd copy allReference Type MemberOfActual object.
The base class system. object has implemented the shortest copy object memberwiseclone () method for all types.
The interface icloneable only contains one method clone (). The classes that inherit this interface can implement clone () based on different optional implementations, which can be deep replication or pre-replication.
You can also use other methods to implement deep replication without limiting the clone () method with the iconeable interface.
The class that can be inherited should avoid implementing the iconeable interface, because this will make all subclasses must implement the icloneable interface.
9. Loop
While and do... While is often used in situations where the loop is uncertain, and the risk coefficient of the endless loop is high.
For and foreach are often used to traverse arrays and collections. Powerful for loop Functions
Foreach is used to traverse the container types that implement ienumberable. Arrays and common container classes such as arraylist and list all implement the ienumberable interface. But it has some limitations.
You cannot change the project value, assign values to the project, or assign values to members within the project through properties. However, the public method of the project can be called.
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text; Namespace Test { Class Useles { Public struct A { Public int _ I; // Change a member through attributes Public int I { Set {_ I = Value ;}} // Change the member using the public Method Public void Modifyi ( Int I) {_ I = I ;} Public override string Tostring (){ Return _ I. tostring ();}} // Test Static void Main ( String [] ARGs ){ A [] Array = New A [3]; Foreach ( A A In Array ){ // A = new A (1); // The compilation fails and the project cannot be changed. // A. _ I = 1; // The compilation fails and the project member variable cannot be changed. // A. I = 1; // The compilation fails and the member variable cannot be changed through the attribute. A. modifyi (1 ); Console . Writeline ();}}}}
10. Using Mechanism
1) Overview
In the. NET environment, managed resources are released by the. NET garbage collector.
Unmanaged resources must be manually released by the programmer.
Two ways to actively and passively release unmanaged resources.
Dispose method of the idisposable Interface
Type your own Finalize method
For any type with unmanaged resources, it is necessary to implement the idisposable dispose method. After using these types, you must manually call the dispose method of the object to release the unmanaged Resources in the object.
If the Finalize method is correctly implemented for the type, the unmanaged resources will be released even if the dispose method is not called, but the resources have been occupied for a long time.
2) The using statement provides an efficient way to call the dispose method of the object.
The Using statement can be used for any type that implements the idisposable interface. For those types that do not implement the idisposable interface, using leads to compilation errors.
The Using statement ensures that the dispose method of the used object is called at the end of the using statement block, regardless of whether an exception is thrown.
C # Add a try/finally statement block to the using statement during compilation. It is essentially the same as an exception capture statement, but it is more concise.