共用方式為


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

屬性
規則識別碼 CA1869
標題 快取並重複使用 'JsonSerializerOptions' 實例
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

JsonSerializerOptions 本機實例會當做 optionsDeserialize 呼叫的引數使用一 Serialize 次。

檔案描述

如果您的程式碼執行多次,使用 的 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);
}

如果對 或 Deserializes_writeOptionss_readOptions 有進一步的呼叫 Serialize ,則應該分別重複使用 或 。

隱藏警告的時機

如果您知道程式碼不會多次具現化 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

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