次の方法で共有


CA2241: 正しい引数を書式指定メソッドに指定します

TypeName

ProvideCorrectArgumentsToFormattingMethods

CheckId

CA2241

分類

Microsoft.Usage

互換性に影響する変更点

なし

原因

WriteLineWriteString.Format などのメソッドに渡される format 文字列引数に、各オブジェクトの引数に対応する書式指定項目が含まれていません (その逆も考えられます)。

規則の説明

WriteLineWrite、および Format などのメソッドに対する引数は、書式指定文字列と、それに続くいくつかの Object インスタンスで構成されます。書式指定文字列は、テキストと、{index[,alignment][:formatString]} という形式の埋め込みの書式指定項目で構成されます。「インデックスは形式にオブジェクトを示すインデックス番号が 0 から始まるの整数です。オブジェクトに、書式指定文字列の対応インデックスがない場合、そのオブジェクトは無視されます。"index" で指定されたオブジェクトが存在しない場合、実行時に FormatException がスローされます。

違反の修正方法

この規則違反を修正するには、各オブジェクトの引数に書式指定項目を指定し、各書式指定項目にオブジェクト引数を指定します。

警告を抑制する状況

この規則による警告は抑制しないでください。

使用例

この規則の 2 つの違反例を次に示します。

Imports System

Namespace UsageLibrary

   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
using System;

namespace UsageLibrary
{
   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));
      }
   }
}