結構設計Struct Design

一般用途的實值型別通常稱為結構,也就是它的 c # 關鍵字。The general-purpose value type is most often referred to as a struct, its C# keyword. 本節提供一般結構設計的指導方針。This section provides guidelines for general struct design.

❌ 請勿為結構提供無參數的函式。❌ DO NOT provide a parameterless constructor for a struct.

遵循此指導方針可建立結構陣列,而不需要在陣列的每個專案上執行此函式。Following this guideline allows arrays of structs to be created without having to run the constructor on each item of the array. 請注意,c # 不允許結構具有無參數的函式。Notice that C# does not allow structs to have parameterless constructors.

❌ 請勿定義可變實數值型別。❌ DO NOT define mutable value types.

可變實值型別有幾個問題。Mutable value types have several problems. 例如,當屬性 getter 傳回實值型別時,呼叫端會收到一份複本。For example, when a property getter returns a value type, the caller receives a copy. 由於複本是以隱含方式建立的,因此開發人員可能不知道它們會改變複本,而不是原始值。Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. 此外,某些語言 (動態語言,特別是) 在使用可變實值型別時遇到問題,因為即使是本機變數,當取值時,也會產生複製。Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

✔️確定所有實例資料都設定為零、false 或 null (適當的) 有效的狀態。✔️ DO ensure that a state where all instance data is set to zero, false, or null (as appropriate) is valid.

這可防止在建立結構陣列時,意外建立不正確實例。This prevents accidental creation of invalid instances when an array of the structs is created.

✔️在實 IEquatable<T> 值型別上執行。✔️ DO implement IEquatable<T> on value types.

Object.Equals實值型別上的方法會造成裝箱,而其預設實並不太有效率,因為它會使用反映。The Object.Equals method on value types causes boxing, and its default implementation is not very efficient, because it uses reflection. Equals 可以有更好的效能,並可進行實作為,使其不會導致裝箱。Equals can have much better performance and can be implemented so that it will not cause boxing.

❌ 請勿明確擴充 ValueType❌ DO NOT explicitly extend ValueType. 事實上,大部分的語言都能防止這種情況。In fact, most languages prevent this.

一般而言,結構可能很有用,但僅適用于不會經常被裝箱的小型、單一且不可變的值。In general, structs can be very useful but should only be used for small, single, immutable values that will not be boxed frequently.

部分©2005、2009 Microsoft Corporation。保留的擁有權限。Portions © 2005, 2009 Microsoft Corporation. All rights reserved.

獲 Pearson Education, Inc. 的授權再版,從 Krzysztof Cwalina 和 Brad Abrams 撰寫,並在 2008 年 10 月 22 日由 Addison-Wesley Professional 出版,作為 Microsoft Windows Development Series 一部份的 Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition 節錄。Reprinted by permission of Pearson Education, Inc. from Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, 2nd Edition by Krzysztof Cwalina and Brad Abrams, published Oct 22, 2008 by Addison-Wesley Professional as part of the Microsoft Windows Development Series.

請參閱See also