C # Summary

Source: Internet
Author: User
Tags protected constructor

C # Method
1: instance constructor and class
2: instance constructor and Structure
3: Type constructor
4: Operator overload method
5. Conversion Operator Method
6. Extension Method
7: Some Methods
1: instance constructor and class
The constructor is a special method that allows you to initialize a type of instance to a good state. When creating an instance of the reference type, allocate memory for the data field of the Instance first, then initialize the additional fields of the object (type object pointer and synchronization index), and call the constructor to set the initial state of the object. Constructors cannot be inherited, so they cannot be modified by virtual, new, override, sealed, and abstract. If no constructor is defined, the compiler will define a public constructor without parameters, but if it is an abstract class, the compiler will define a protected constructor without parameters.
Creating an instance of a class does not have to call the constructor.
1: Use the MemberwiseClone () method of the Object. The role is to create the current System. A superficial copy of an Object. The internal working mechanism is to allocate memory, initialize additional fields of the Object (type Object pointer and synchronization index), and then copy the byte data of the source Object to the new Object. The following code shows that MemberwiseClone () implements object replication instead of simple object reference. Copy codeThe Code is as follows: class Program
{
Public int X;
Static void Main (string [] args)
{
Program p = new Program ();
P. X = 1;
Program q = (Program) p. MemberwiseClone ();
Program z = p;
P. X = 2;
Console. WriteLine ("p. X =" + p. X); // output: p. X = 2
Console. WriteLine ("q. X =" + q. X); // output: q. X = 1
Console. WriteLine ("z. X =" + z. X); // output: z. X = 2
Console. Read ();
}
}

2: deserialization. During network programming, an object is often serialized into binary and then transmitted. The receiver deserializes the object to the original object. deserialization uses classes.
System. Runtime. Serialization. FormatterServices method public static object GetUninitializedObject (Type type) or
Public static object GetSafeUninitializedObject (Type type) allocates memory, and no constructor is called inside the two methods to be deserialized.
The field initialization code is automatically added to the corresponding constructor by the compiler, and the non-static field initialization code is automatically added to the instance constructor, the static field initialization code is added to the static constructor. If your code has multiple fields initialized and multiple constructor functions, the initialization code will have a copy in each constructor, which will undoubtedly make your generated files (such as DLL and EXE files) larger.
The code to prove this is as follows:Copy codeThe Code is as follows: public class SomeType
{
Public int x = 1, y = 2, z = 3;
Public SomeType (){}
Public SomeType (int x, int y)
{
This. x = x;
This. y = y;
}
Public SomeType (int x)
{
This. x = x;
}
}
// The Code of SomeType (int x, int y) after IL decompilation is as follows:
. Method public hidebysig specialname rtspecialname
Instance void. ctor (int32 x,
Int32 y) Pencil managed
{
// Code size 45 (0x2d)
. Maxstack 8
IL_0000: ldarg.0
IL_0001: ldc. i4.1
IL_0002: st1_int32 MyTest. SomeType: x
IL_0007: ldarg.0
IL_0008: ldc. i4.2
IL_0009: st1_int32 MyTest. SomeType: y
IL_000e: ldarg.0
IL_000f: ldc. i4.3
IL_0010: st1_int32 MyTest. SomeType: z
IL_0015: ldarg.0
IL_0016: call instance void [mscorlib] System. Object:. ctor ()
IL_001b: nop
IL_001c: nop
IL_001d: ldarg.0
IL_001e: ldarg.1
IL_001f: st1_int32 MyTest. SomeType: x
IL_0024: ldarg.0
IL_0025: ldarg.2
IL_0026: st1_int32 MyTest. SomeType: y
IL_002b: nop
IL_002c: ret
} // End of method SomeType:. ctor

First, the initialization code is executed. Other constructors contain the initialization code and then the value assignment code in the constructor is executed. To solve the code expansion problem, the method is very simple, write the initialization code in the no-argument constructor to call other constructor functions.
2: instance constructor and Structure
The working method of the value type is different from that of the reference type. In fact, the value type does not need to define the constructor. The Earth cannot prevent the value type instantiation, And the compiler will not produce the default constructor, if you show that no parameter constructor is declared, the compilation will fail. The error "the structure cannot contain an explicit non-parameter constructor" is returned ". Because the value type exists in the stack and does not need to be referenced in the heap data, we can directly assign values when defining (int I = 0; string s = "a"; Point p; p. X = 2;) it does not need new at all. Of course new is acceptable. Calling the constructor will Initialize all fields to the default values of the corresponding type. The example is as follows:Copy codeThe Code is as follows: public struct Point
{
Public int x, y;
// Public Point () {}// error: the structure cannot contain explicit non-parameter Constructor
// Public int z = 4; // error: the initial value of the Instance field cannot be found in the structure.
// Public Point (int x) // The Field "Point. y "must be fully assigned. To solve this problem, add a default value to y manually,
// You can also add this = new Point (); initialize the values of all fields to 0 or null
//{
// This. x = x;
//}
Public void Test ()
{
Point p;
P. x = 1;
P. y = 2;
Console. WriteLine (p. x + "," + p. y); // output 1, 2
}
}

Structure Features:
1: the definition of a constructor without parameters cannot be displayed.
2: fields cannot be initialized during definition.
3: When declaring a constructor with parameters, all fields must be initialized.
3: Type constructor
The instance constructor is a static constructor. Its function is to set the initialization status of the type. A static constructor can have only one and has no parameters and cannot have access modifiers, the default value is private, which is called and executed by the compiler. Example:Copy codeThe Code is as follows: public class SomeType
{
Public static int x = 520;
Static SomeType ()
{
X = 112;
}
}

// Use. NET reflector to view the source code, as shown below:
Public class SomeType
{
Public static int x;
Static SomeType ()
{
X = 520;
X = 0x70;
}
Public SomeType (){}
}

When defining and initializing static fields, the compiler automatically generates a Type constructor (static constructor) and inserts the static field initialization code before the Type constructor, from the code above, we can see that only one class is required for initialization during definition and in the Type constructor, And the hexadecimal 112 is 0x70, therefore, we don't need to make a fuss when we see hexadecimal in the code. It doesn't involve performance issues at all. If static fields are defined, but no one is initialized, the compiler will not generate a Type constructor. However, static fields will still be initialized. In fact, both static and non-static fields will be automatically initialized by the compiler. int type Initialization is 0; bool: False; string: null, this is why when you instantiate an object, some fields are not initialized, but no error is reported, and you know that the value of the uninitialized string is null, that is to say, the compiler will help you initialize fields that you have not initialized. However, the local variables defined in the method need to be initialized by yourself. If you have not initialized them, an error "using unassigned local variable X" is reported ".
4: Operator overload method
To implement Operator overloading, you only need to ensure the following two points. The others are floating clouds:
1: The operator overload methods must be public and static.
2: The operator overload method must have at least one parameter of the same type as the method currently defined. The reason for this condition is that the compiler finds the operation method to bind within a reasonable period of time. The example is as follows:Copy codeThe Code is as follows: public class Complex
{
Public int data;
Public Complex (int data)
{
This. data = data;
}
Public static Complex operator + (Complex c1, Complex c2)
{
Return new Complex (c1.data + c2.data );
}
Public void Test ()
{
Complex c1 = new Complex (1 );
Complex c2 = new Complex (2 );
Complex c3 = c1 + c2;
Console. WriteLine (c3.data); // output 3
}
}

5. Conversion Operator Method
To implement the conversion operator method, the condition is the same as that of the operator overload method. The example is as follows:Copy codeThe Code is as follows: public class Rational
{
Public Rational (int data)
{
This. data = data;
}
Public Rational (char data)
{
This. data = (int) data;
}
// Implicit type conversion: int-> Rational
Public static implicit operator Rational (int data)
{
Return new Rational (data );
}
// Implicit type conversion: char-> Rational
Public static implicit operator Rational (char data)
{
Return new Rational (data );
}
// Convert the display type to Rational-> int
Public static explicit operator int (Rational val)
{
Return val. data;
}
// Convert the display type to Rational-> char
Public static explicit operator char (Rational val)
{
Return Convert. ToChar (val. data );
}
Public void Test ()
{
Rational r1 = 1; // implicitly converts the int type to Rational
Rational r2 = '2'; // implicitly converts the char type to Rational
Int I = (int) r1; // converts the Rational type to int
Char c = (char) r2; // convert the Rational type display to char
Console. WriteLine ("I =" + I); // output: I = 1
Console. WriteLine ("c =" + c); // output: c = 2
}

Int data;
}

The implementation principle of implicit and display type conversion is so simple. In C ++, implicit type conversion does not require you to write code, as long as there is a corresponding public constructor, for example, if int is converted to Rational, you only need to have the constructor public Rational (int data), such as Rational r = 1; the compiler will make every effort to find a method to convert the int type to Rational. When it finds this constructor, he will help you with the conversion without saying anything, because sometimes it is very boring, an int type becomes Rational for no reason, but you don't know what is going on. Sometimes, to solve this problem, you have to define a class (Uint) to encapsulate int, then change the constructor to Rational (Uint data). C # does not have this problem. Of course, if you want to implement implicit type conversion, write your own code.
6. Extension Method
Conditions for implementing the extension method:
1: The class defining the extension method must be non-generic static class.
2: this class must have its own scope, that is, it cannot be an internal class.
3: The methods must be public and static.
4: The first parameter of the method must be modified with this. The first parameter is the type to be extended. The example is as follows:
Copy codeThe Code is as follows: public static class StringExtensions
{
Public static int ToInt (this string s)
{
Return Convert. ToInt32 (s );
}
Public void Test ()
{
String s = "2 ";
Console. WriteLine (s. ToInt ());
}
}

7: Some Methods
You know

Related Article

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.