When should I use a struct instead of a class?

后端 未结 15 2125
臣服心动
臣服心动 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:13

    Use a class if:

    • Its identity is important. Structures get copied implicitly when being passed by value into a method.
    • It will have a large memory footprint.
    • Its fields need initializers.
    • You need to inherit from a base class.
    • You need polymorphic behavior;

    Use a structure if:

    • It will act like a primitive type (int, long, byte, etc.).
    • It must have a small memory footprint.
    • You are calling a P/Invoke method that requires a structure to be passed in by value.
    • You need to reduce the impact of garbage collection on application performance.
    • Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types.
      • Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values.
    • You do not need to inherit from a base class (other than ValueType, from which all structs inherit).
    • You do not need polymorphic behavior.

提交回复
热议问题