The difference between C# structure and class

The struct is a lightweight version of the class. Structures are value types and can be used to create objects that behave like built-in types.

Compare

Structures and classes share many characteristics, but they have the following limitations compared to classes.

The structure cannot have a default constructor (parameterless constructor) or destructor, and all fields must be assigned values ​​in the constructor.

 public struct Coords
  {
    
    
      public double x;
      public double y;

      public Coords() //错误,不允许无参构造函数
      {
    
    
          this.x = 3;
          this.y = 4;
      }

      public Coords(double x) //错误,构造函数中必须给所有字段赋值
      {
    
    
          this.x = x;
      }

      public Coords(double x) //这个是正确的
      {
    
    
          this.x = x;
          this.y = 4;
      }

      public Coords(double x, double y) //这个是正确的
      {
    
    
          this.x = x;
          this.y = y;
      }
  }

The structure is a value type, and it is copied during assignment.

Structures are value types, and classes are reference types.

The structure can be instantiated without using the new operator. E.g:

  public struct Coords
  {
    
    
      public double x;
      public double y;
  }

  static void Main()
  {
    
    
      Coords p;
      p.x = 3;
      p.y = 4;
      Console.WriteLine($"({p.x}, {p.y})");  // 输出: (3, 4)
  }

A structure cannot inherit from another structure or class, and a class cannot inherit a structure. All structures directly inherit from the abstract class System.ValueType, which in turn inherits from System.Object.

The structure cannot be a base class. Therefore, the structure cannot be abstract and is always implicitly sealed.

It is not allowed to use abstract and sealed modifiers on structures, nor is it allowed to use protected or protected internal modifiers on structure members.

The function members in the structure cannot be abstract or virtual. The override modifier only allows to override the methods inherited from System.ValueType.

Instance attributes or fields are not allowed to contain initializers in the structure. However, the structure allows static properties or fields to contain initializers. E.g:

  public struct Coords
  {
    
    
      public double x = 4; //错误, 结构体中初始化器不允许实例字段设定初始值
      public static double y = 5; // 正确
      public static double z {
    
     get; set; } = 6; // 正确
  }

Structures can implement interfaces.

When to use a structure or class?

To answer this question, we should understand their differences well.

Sequence number structure (struct) Class (class)
1 The structure is a value type, which can be allocated on the stack or inline in the containing type. The class is a reference type, allocated on the heap and garbage collected.
2 The allocation and release of value types are usually more cost-effective than the allocation and release of reference types. Assignment of large reference types is cheaper than assignment of large value types.
3 In the structure, each variable contains its own data copy (except ref and out parameter variables), and the operation of one variable will not affect the other variable. In a class, two variables can contain references to the same object, and any operation on one variable will affect the other variable.
In this way, the structure (struct) can only be used when determining the following situations:

It logically represents a single value, such as basic types (int, double, etc.).

It is immutable.

It will not be boxed and unboxed frequently.

In all other cases, the type should be defined as a class.

Structure example:

struct Location
{
    
    
    public int x, y;
    public Location(int x, int y)
    {
    
    
        this.x = x;
        this.y = y;
    }
}

static void Main()
{
    
    
    Location a = new Location(20, 20);
    Location b = a;
    a.x = 100;
    Console.WriteLine(b.x);
}

The output will be 20. The value of "b" is a copy of "a", so "b" is not affected by the change of "ax". But in the class, the output will be 100 because the variables "a" and "b" refer to the same object.

The following is the translator's supplement

Structure instance and class instance
The memory of structure instance is allocated on the stack, and the occupied memory is reclaimed along with the type or method in which it is declared. This is one reason to copy the structure when assigning. In contrast, the memory of a class instance is allocated on the heap. When all references to the class instance are out of range, the memory allocated for the class instance will be automatically reclaimed (garbage collection) by the common language runtime.

The value equality of
structure instances The comparison of two structure instances is based on the comparison of values, while the comparison of class instances is the comparison of their references.

To determine whether the instance fields in two structure instances have the same value, you can use the ValueType.Equals method. Since all structures are implicitly inherited from System.ValueType, this method can be called directly on their objects, as shown in the following example:

public struct Person
{
    
    
    public string Name;
    public int Age;
    public Person(string name, int age)
    {
    
    
        Name = name;
        Age = age;
    }
}

static void Main()
{
    
    
    Person p1 = new Person("技术译站", 100);
    Person p2;
    p2.Name = "技术译站";
    p2.Age = 100;

    if (p2.Equals(p1))
        Console.WriteLine("p2 和 p1 有相同的值。");

    Console.ReadKey();
}
// 输出: p2 和 p1 有相同的值。

Guess you like

Origin blog.csdn.net/CharmaineXia/article/details/109402115