CA1869:快取並重複使用 'JsonSerializerOptions' 實例

屬性
規則識別碼 CA1869
職稱 快取並重複使用 『JsonSerializerOptions』 實例
類別 效能
修正是造成中斷還是不中斷 不中斷
在 .NET 10 中預設啟用 作為建議
適用語言 C# 與 Visual Basic

原因

一個JsonSerializerOptions 的本機實例會作為 optionsSerialize 呼叫的參數使用一次。

規則描述

如果您的程式代碼多次執行時,每次都使用本機 JsonSerializerOptions 實例來進行序列化或反序列化,可能會大幅降低應用程式的效能,因為 System.Text.Json 會在內部將序列化相關的中繼資料快取至提供的實例。

如何修正違規

您可以使用單一模式,以避免每次執行程式碼時建立新的 JsonSerializerOptions 實例。

範例

下列代碼段顯示 CA1869 的兩個違規:

static string Serialize<T>(T value)
{
    JsonSerializerOptions jsonOptions = new()
    {
        WriteIndented = true
    };

    return JsonSerializer.Serialize(value, jsonOptions);
}

static T Deserialize<T>(string json)
{
    return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions { AllowTrailingCommas = true });
}

下列代碼段會修正違規:

private static readonly JsonSerializerOptions s_writeOptions = new()
{
    WriteIndented = true
};

private static readonly JsonSerializerOptions s_readOptions = new()
{
    AllowTrailingCommas = true
};

static string Serialize<T>(T value)
{
    return JsonSerializer.Serialize(value, s_writeOptions);
}

static T Deserialize<T>(string json)
{
    return JsonSerializer.Deserialize<T>(json, s_readOptions);
}

如果對 SerializeDeserialize 有進一步的呼叫,或者對 s_writeOptionss_readOptions 有進一步的呼叫,則應分別重用 s_writeOptionss_readOptions

隱藏警告的時機

如果您知道程式代碼不會多次具現化 JsonSerializerOptions 實例,則隱藏此警告是安全的。

隱藏警告

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

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

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

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

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