When should I use a struct instead of a class?

后端 未结 15 2273
臣服心动
臣服心动 2020-11-22 13:00

MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?

Some people might ha

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 13:19

    MSDN has the answer: Choosing Between Classes and Structures.

    Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.

    Do not define a structure unless the type has all of the following characteristics:

    • It logically represents a single value, similar to primitive types (integer, double, and so on).
    • It has an instance size smaller than 16 bytes.
    • It is immutable.
    • It will not have to be boxed frequently.

提交回复
热议问题