Structure in C#, the difference between C# and class

Structure in C#, the difference between C# and class

struct declaration

  • You cannot use the keyword to structdeclare a structure; you can use newto declare a structure

    //CoOrds 是一个结构体
    CoOrds coords1;//直接声明
    CoOrds coords1 = new CoOrds();//使用new关键字, 调用默认构造函数
    CoOrds coords2 = new CoOrds(10, 10);//使用new关键字, 调用参数化构造函数

instantiation of struct

  • Use default constructor and parameterized constructor to demonstrate structinitialization :

    public struct CoOrds
    {
      public int x, y;
    
      public CoOrds(int p1, int p2)
      {
          x = p1;
          y = p2;
      }
    }
    
    // Declare and initialize struct objects.
    class TestCoOrds
    {
      static void Main()
      {
          // Initialize:   
          CoOrds coords1 = new CoOrds();//使用默认构造函数
          CoOrds coords2 = new CoOrds(10, 10);//使用参数化构造函数
    
          // Display results:
          Console.Write("CoOrds 1: ");//使用默认构造函数, 此时所有成员分配默认值
          Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);
    
          Console.Write("CoOrds 2: ");//使用参数化构造函数, 此时成员分配参数
          Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);
    
          // Keep the console window open in debug mode.
          Console.WriteLine("Press any key to exit.");
          Console.ReadKey();
      }
    }
    /* Output:
      CoOrds 1: x = 0, y = 0
      CoOrds 2: x = 10, y = 10
    */
    
  • This example demonstrates a structunique feature. This feature creates CoOrds objects without using the newoperator . If you structreplace with class, the program will not compile.

    public struct CoOrds
    {
      public int x, y;
    
      public CoOrds(int p1, int p2)
      {
          x = p1;
          y = p2;
      }
    }
    
    // Declare a struct object without "new."
    class TestCoOrdsNoNew
    {
      static void Main()
      {
          // 声明一个结构体, 字段将保持为未分配状态
          CoOrds coords1;
    
          // 字段必须在初始化所有字段之后才可使用对象
          coords1.x = 10;
          coords1.y = 20;
    
          // Display results:
          Console.Write("CoOrds 1: ");
          Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);
    
          // Keep the console window open in debug mode.
          Console.WriteLine("Press any key to exit.");
          Console.ReadKey();
      }
    }
    // Output: CoOrds 1: x = 10, y = 20

struct constructor

  • If a struct object is instantiated using the default, no-argument constructor, all members are assigned according to their default values .
  • When writing a struct parameterized constructor, you must explicitly initialize all members
  • To instantiate a structure, it is not necessary to use the newoperator . In this case, no constructors are called, which improves allocation efficiency. However, the fields will remain unassigned and all fields must be initialized before the object can be used. This includes values ​​for properties that cannot be passed getor setauto-implemented.

The advantages of structs

  • structTypes are suitable for representing lightweight objects such as Point, RectangleandColor
  • Although it's as convenient to use it to represent a point as a class with Auto-Implemented Properties , in some cases it may be more efficient to use a struct. For example, if you declare an array with 1000 objects , you will allocate extra memory for referencing each object; in this case, using a struct will be less expensive.Point
  • Unless reference type semantics are required, declaring smaller classes as structs can improve the processing efficiency of the system.

Inheritance of structs

  • A struct cannot inherit from another struct or class, and it cannot be the base class of a class.
  • Structures can also implement interfaces in the same way as classes.

structs and classes

  • Classes are reference types. After an object of a class is created, the variable to which the object is assigned retains only a reference to the corresponding memory; structs are value types. When a structure is created, the variable to which the structure is assigned retains the actual data of the structure
  • When an object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable will be reflected in the other because they refer to the same data; when a structure is assigned to a new variable, the structure is copied. Therefore, the new variable and the original variable contain copies of the same data (two in total). Changes made to one copy do not affect the other copy.
  • In general, classes are used for more complex behavior or when data should be modified after the class object is created. Structures are suitable for small data structures that contain most of the data that will not be modified after the structure is created.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324749946&siteId=291194637