CA1863:使用 'CompositeFormat'

屬性
規則識別碼 CA1863
標題 使用 CompositeFormat
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

程式代碼會呼叫 String.Format(String, Object[])StringBuilder.AppendFormat(String, Object[]) 具有 static 尚未快取至 CompositeFormat 實例的格式字串。

檔案描述

在運行時間剖析格式字串的成本很高。 此規則會找出程式代碼中的位置,您可以在其中快取 CompositeFormat 並使用 實例做為格式化作業的自變數,而不是傳入原始格式字串。 CompositeFormat實例會在建立時剖析複合格式字串,這表示字串格式設定的「經常性路徑」可以執行得更快。

如何修正違規

藉由呼叫 CompositeFormat.Parse(String) ,並將其傳遞至String.Format(IFormatProvider, CompositeFormat, Object[])StringBuilder.AppendFormat(IFormatProvider, CompositeFormat, Object[])取代原始格式字串,以建立的實例CompositeFormat

範例

下列範例顯示規則的兩個違規:

class C
{
    private static readonly string StaticField = "Format one value: {0}";

    static void Main()
    {
        _ = string.Format(StaticField, 42);

        StringBuilder sb = new();
        sb.AppendFormat(StaticField, 42);
    }
}

下列範例顯示修正這兩個違規的程式代碼:

class C
{
    private static readonly CompositeFormat StaticField = CompositeFormat.Parse("Format one value: {0}");

    static void Main()
    {
        _ = string.Format(null, StaticField, 42);

        StringBuilder sb = new();
        sb.AppendFormat(null, StaticField, 42);
    }
}

隱藏警告的時機

如果效能不相關,請放心地隱藏此規則的診斷。

隱藏警告

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

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

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

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

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