CA2241:必須提供格式化方法的正確引數

屬性
規則識別碼 CA2241
標題 必須提供格式化方法的正確引數
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

format傳遞至、 WriteSystem.String.FormatWriteLine方法的字串自變數不包含對應至每個物件自變數的格式專案,反之亦然。

根據預設,此規則只會分析對先前所述的三個方法的呼叫,但這是可設定

檔案描述

WriteFormatWriteLine方法的自變數是由格式字串所組成,後面接著數System.Object個實例。 格式字串是由表單 {index[,alignment][:formatString]}的文字和內嵌格式專案所組成。 'index' 是以零起始的整數,會指出需要格式化的物件。 如果物件在格式字串中沒有對應的索引,則會忽略 物件。 如果 'index' 指定的物件不存在, System.FormatException 則會在執行時間擲回 。

如何修正違規

若要修正此規則的違規,請為每個物件自變數提供格式專案,併為每個格式專案提供物件自變數。

隱藏警告的時機

請勿隱藏此規則的警告。

設定程式代碼以分析

使用下列選項來設定其他方法來執行此規則。

其他字串格式方法

您可以設定此規則應該分析的其他字串格式方法名稱。 例如,若要指定名稱 MyFormat 為字串格式方法的所有方法,您可以將下列機碼/值組新增至 專案中的 .editorconfig 檔案:

dotnet_code_quality.CA2241.additional_string_formatting_methods = MyFormat

選項值中允許的方法名稱格式(以 |分隔):

  • 僅限方法名稱(包含名稱的所有方法,不論包含類型或命名空間為何)
  • 符號 文件識別碼格式的完整名稱,具有選擇性 M: 前置詞。

範例:

選項值 摘要
dotnet_code_quality.CA2241.additional_string_formatting_methods = MyFormat 比對編譯中名為 MyFormat 的所有方法。
dotnet_code_quality.CA2241.additional_string_formatting_methods = MyFormat1|MyFormat2 比對編譯中名為 MyFormat1MyFormat2 的所有方法。
dotnet_code_quality.CA2241.additional_string_formatting_methods = NS.MyType.MyFormat(ParamType) 比對具有指定完整簽章的特定方法 MyFormat
dotnet_code_quality.CA2241.additional_string_formatting_methods = NS1.MyType1.MyFormat1(ParamType)|NS2.MyType2.MyFormat2(ParamType) 比對特定方法和MyFormat1MyFormat2個別的完整簽章。

自動判斷其他字串格式方法

您可以設定分析器來自動嘗試判斷字串格式方法,而不是指定其他字串格式方法的明確清單。 預設會停用此選項。 如果啟用此選項,任何具有 string format 參數後接 params object[] 參數的方法都會被視為字串格式方法:

dotnet_code_quality.CA2241.try_determine_additional_string_formatting_methods_automatically = true

範例

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

Imports System

Namespace ca2241

    Class CallsStringFormat

        Sub CallFormat()

            Dim file As String = "file name"
            Dim errors As Integer = 13

            ' Violates the rule.
            Console.WriteLine(String.Format("{0}", file, errors))

            Console.WriteLine(String.Format("{0}: {1}", file, errors))

            ' Violates the rule and generates a FormatException at runtime.
            Console.WriteLine(String.Format("{0}: {1}, {2}", file, errors))

        End Sub

    End Class

End Namespace
class CallsStringFormat
{
    void CallFormat()
    {
        string file = "file name";
        int errors = 13;

        // Violates the rule.
        Console.WriteLine(string.Format("{0}", file, errors));

        Console.WriteLine(string.Format("{0}: {1}", file, errors));

        // Violates the rule and generates a FormatException at runtime.
        Console.WriteLine(string.Format("{0}: {1}, {2}", file, errors));
    }
}