Why do we need struct? (C#)

后端 未结 9 1913
盖世英雄少女心
盖世英雄少女心 2021-02-05 21:18

To use a struct, we need to instantiate the struct and use it just like a class. Then why don\'t we just create a class in the first place?

9条回答
  •  一整个雨季
    2021-02-05 21:23

    A major difference between the semantics of class and struct is that structs have value semantics. What is this means is that if you have two variables of the same type, they each have their own copy of the data. Thus if a variable of a given value type is set equal to another (of the same type), operations on one will not affect the other (that is, assignment of value types creates a copy). This is in sharp contrast to reference types.

    There are other differences:

    1. Value types are implicitly sealed (it is not possible to derive from a value type).
    2. Value types can not be null.
    3. Value types are given a default constructor that initialzes the value type to its default value.
    4. A variable of a value type is always a value of that type. Contrast this with classes where a variable of type A could refer to a instance of type B if B derives from A.

    Because of the difference in semantics, it is inappropriate to refer to structs as "lightweight classes."

提交回复
热议问题