Struct vs. Class

Struct vs. Class

這篇介紹Struct和Class兩者資料結構的特性以及使用時機。

兩者比較

1
2
3
4
5
Class				Struct
Reference type value type
可繼承 不可繼承
可變更 不可變更
不能有預設建構子

使用時機

1
2
3
4
5
6
7
8
9
當下列4個條件完全符合時,才建議使用Struct資料結構。
沒有完全符合條件時,建議使用Class資料結構。
defining a struct unless the type has all of the following characteristics:

1.It logically represents a single value, similar to primitive types (int, double, > > etc.).
2.It has an instance size under 16 bytes.
3.It is immutable.
4.It will not have to be boxed frequently.
In all other cases, you should define your types as classes.