閱讀英文版本

分享方式:


讓結構欄位成為可寫入的 (IDE0064)

財產 價值
規則標識碼 IDE0064
標題 讓結構欄位成為可寫入的欄位
類別 CodeQuality
子類別 語言規則(修飾詞偏好)
適用的語言 C#

概述

此規則會偵測結構中包含一個或多個 readonly 欄位,且在建構函式之外對 this 進行賦值的情況。 此規則建議將 readonly 字段轉換成非唯讀,也就是可寫入的。 將這類結構欄位標示為 readonly 可能會導致非預期的行為,因為指派給欄位的值可以在建構函式外部指派 this 時變更。

選項

此規則沒有相關聯的程式代碼樣式選項。

C#
// Code with violations
struct MyStruct
{
    public readonly int Value;

    public MyStruct(int value)
    {
        Value = value;
    }

    public void Test()
    {
        this = new MyStruct(5);
    }
}

// Fixed code
struct MyStruct
{
    public int Value;

    public MyStruct(int value)
    {
        Value = value;
    }

    public void Test()
    {
        this = new MyStruct(5);
    }
}

隱藏警告

如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

C#
#pragma warning disable IDE0064
// The code that's violating the rule is on this line.
#pragma warning restore IDE0064

若要停用檔案、資料夾或項目的規則,請將其嚴重性設定為 組態檔中的 none

ini
[*.{cs,vb}]
dotnet_diagnostic.IDE0064.severity = none

若要停用此整個規則類別,請將類別的嚴重性設定為 組態檔中的 none

ini
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-CodeQuality.severity = none

如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。

另請參閱