What's the difference between struct and class in .NET?

前端 未结 19 1617
一向
一向 2020-11-22 01:51

What\'s the difference between struct and class in .NET?

19条回答
  •  野性不改
    2020-11-22 02:13

    From Microsoft's Choosing Between Class and Struct ...

    As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

    CONSIDER a struct instead of a class:

    • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

    X AVOID a struct unless the type has all of the following characteristics:

    • It logically represents a single value, similar to primitive types (int, double, etc.).
    • It has an instance size under 16 bytes.
    • It is immutable. (cannot be changed)
    • It will not have to be boxed frequently.

提交回复
热议问题