SoFunction
Updated on 2025-03-06

Summary and detailed explanation of C# method

C# method1: Instance constructor and class
2: Instance constructor and structure
3: Type constructor
4: Operator overload method
5: Convert operator method
6: Extended Method
7: Some methods
1: Instance constructor and class
A constructor is a special method that allows initialization of an instance of a type to be good state. When creating an instance of a reference type, first allocate memory for the data fields of the instance, then initialize the additional fields of the object (type object pointer and synchronous index), and finally call the constructor to set the initial state of the object. The constructor cannot be inherited, so it cannot be modified by virtual, new, override, sealed and abstract. If no constructor is displayed, 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 necessarily require calling the constructor.
1: Use the MemberwiseClone() method of Object. Its function is to create the current shallow copy. 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 into the new object. From the following code, we can see that MemberwiseClone() implements object copying, rather than simple object references.

Copy the codeThe code is as follows:

class Program
    {
        public int X;
        static void Main(string[] args)
        {
            Program p = new Program();
            = 1;
            Program q = (Program)();
            Program z = p;
            = 2;
("=" + );//Output: =2
("=" + );//Output: =1
("=" + );//Output: =2
            ();
        }
    }

2: Deserialization. When programming a network, an object is often serialized into binary and then transmitted, and the receiver deserializes it into the original object. The deserialization uses a class
Method public static object GetUninitializedObject(Type type) or
public static object GetSafeUninitializedObject(Type type) allocates memory, and the constructor to be deserialized is not called inside these two methods.
The code to prove this is as follows:
Copy the codeThe code is as follows:

public class SomeType
    {
        public  int x=1,y=2,z=3;
        public SomeType() { }
        public SomeType(int x, int y)
        {
            = x;
            = y;
        }
        public SomeType(int x)
        {
            = x;
        }
}
//After decompiling with IL, the code of method SomeType(int x, int y) is as follows
.method public hidebysig specialname rtspecialname
        instance void  .ctor(int32 x,
                             int32 y) cil managed
{
// Code size       45 (0x2d)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.1
  IL_0002:  stfld      int32 ::x
  IL_0007:  ldarg.0
  IL_0008:  ldc.i4.2
  IL_0009:  stfld      int32 ::y
  IL_000e:  ldarg.0
  IL_000f:  ldc.i4.3
  IL_0010:  stfld      int32 ::z
  IL_0015:  ldarg.0
  IL_0016:  call       instance void [mscorlib]::.ctor()
  IL_001b:  nop
  IL_001c:  nop
  IL_001d:  ldarg.0
  IL_001e:  ldarg.1
  IL_001f:  stfld      int32 ::x
  IL_0024:  ldarg.0
  IL_0025:  ldarg.2
  IL_0026:  stfld      int32 ::y
  IL_002b:  nop
  IL_002c:  ret
} // end of method SomeType::.ctor

The initialization code is first executed. The other constructors contain the initialization code, and then the assignment code in the constructor is executed. To solve the problem of code expansion, the method is very simple. Write the initialization code in the parameterless constructor and let other constructors call it.
2: Instance constructor and structure
The working method of value types is completely different from the reference type. The value types do not actually require a constructor to be defined. Earthlings cannot prevent instantiation of value types, and the compiler will not produce the default parameterless constructor at all. If you display a declaration parameterless constructor, the compilation cannot be passed at all, and an error "The structure cannot contain an explicit parameterless constructor." Since the value type exists on the stack, there is no need to reference the data in the heap at all, we can directly assign values ​​when defining it. (int i=0; string s=”a”;Point p;=2;) It does not need new at all. Of course new is OK. Calling the constructor will initialize all fields into the default values ​​of the corresponding type, as shown below:
Copy the codeThe code is as follows:

public struct Point
    {
        public int x, y;
//public Point() { }//Error: The structure cannot contain explicit parameterless constructor
//public int z = 4;//Error: There cannot be instance field initializer in the structure
//public Point(int x) //Before control returns to the caller, the field "" must be fully assigned. To solve this problem, manually add a default value to y.
//You can also add this=new Point(); initialize the values ​​of all fields to 0 or null
        //{
        //    = x;
        //}
        public void Test()
        {
            Point p;
            = 1;
            = 2;
(+","+);//Output 1,2
        }
    }

Structural features:
1: The definition without parameter constructor cannot be displayed
2: Cannot initialize when defining fields
3: When declaring a parameter constructor, all fields must be initialized
3: Type constructor
An instance constructor is a static constructor. Its function is to set the initialization state of the type. There can only be one static constructor, and it is without parameters. There cannot be access modifier modification. The default is private, which is executed by the compiler call. Examples are as follows:
Copy the 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 follows
    public class SomeType
    {
        public static int x ;
        static SomeType()
        {
            x = 520;
            x = 0x70;
        }
        public SomeType() { }
    }

When defining static fields and initializing, the compiler will automatically generate a type constructor (static constructor) and insert the initialization code of the static field in front of the type constructor. From the above code, it can be seen that only one is required for initialization and initialization in the type constructor during definition. There is also a hexadecimal of 112, which is 0x70, so there is no need to make a fuss about seeing hexadecimal in the code. It does not involve performance issues at all. If a static field is defined but no one is initialized, the compiler will not generate a type constructor. However, static fields will still be initialized. In fact, whether static or non-static fields will be automatically initialized by the compiler. The int type is initialized to 0; bool: False; string: null, which is why when you instantiate an entity, you do not initialize some fields but will not report an error. Moreover, you know that the value of the string that is not initialized is null, which means that the compiler will help you initialize the fields that you have not initialized. However, the local variables defined in the method need to be initialized by themselves. If you do not initialize, an error "used the unassigned local variable X".
4: Operator overload method
To implement operator overloading, you only need to ensure the following two points, and the others are all over the world:
1: Operator overloading methods must be public and static methods
2: The operator overload method has at least one parameter type the same as the type currently defined by this method. The reason for this condition is to enable the compiler to find the operation method to bind within a reasonable time, such as the following
Copy the codeThe code is as follows:

public class Complex
    {
        public int data;
        public Complex(int data)
        {
            = data;
        }
        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(+);
        }
        public void Test()
        {
            Complex c1 = new Complex(1);
            Complex c2 = new Complex(2);
            Complex c3 = c1 + c2;
();//Output 3
        }
    }

5: Convert operator method
To implement the conversion operator method, the conditions and the conditions of the operator overload method are the same. Examples are as follows:
Copy the codeThe code is as follows:

public class Rational
    {
        public Rational(int data)
        {
            = data;
        }
        public Rational(char 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);
        }
//Display type conversion Rational->int
        public static explicit operator int(Rational val)
        {
            return ;
        }
//Display type conversion Rational->char
        public static explicit operator char(Rational val)
        {
            return ();
        }
        public void Test()
        {
Rational r1 = 1;//Implicitly convert the int type to Rational
Rational r2 = '2';//Implicitly convert char type to Rational
int i = (int)r1;//Convert Rational type display to int
char c = (char)r2;//Convert Rational type display to char
("i=" + i);//Output: i=1
("c=" + c);//Output: c=2
        }
        
        int data;
    }

6: Extended Method
Conditions for implementing the extension method:
1: The class that defines the extension method must be a 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, and the first parameter is the type you want to extend, as shown below:
Copy the 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";
            (());
        }
}

7: Some methods
You know