界: Code Quality

程式碼品質不佳,會導致無法預料的行為。從使用者的角度來看,這通常表現為可用性不佳。對於攻擊者而言,這提供了以意想不到的方式向系統施加壓力的機會。

Code Correctness: Readonly Collection Reference

Abstract
此唯讀關鍵字會強制執行此規則:必須初始化宣告時或在建構函式中的變數,且不能在任何其他位置修改變數。對於值類型來說,這可以如預期般執行,但是物件和清單的內容依然可以修改,即使已將其宣告為私用唯讀。
Explanation
從 getter-only 屬性傳回 private readonly 清單變數將會允許呼叫程式碼修改該清單的內容,如此可有效提供清單寫入存取權,並阻止程式設計師將它設為 private readonly 的計畫。

範例 1:下列程式碼包含宣告為 private readonly_item 清單。

class Order
{
private readonly List<string> _item = new List<string>();
public IEnumerable<string> Item { get { return _item; } }

public Order()
{
/*class initialize */
}

/*some important function......*/
}
References
[1] Standards Mapping - CIS Azure Kubernetes Service Benchmark 1
[2] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 5
[3] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[4] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
[5] Standards Mapping - Common Weakness Enumeration CWE ID 398
desc.structural.dotnet.code_correctness_readonly_collection_reference