Udostępnij za pośrednictwem


CA2241: Zapewniają prawidłowe argumenty metod formatowania

TypeName

ProvideCorrectArgumentsToFormattingMethods

CheckId

CA2241

Kategoria

Microsoft.Usage

Złamanie zmiany

Bez podziału

Przyczyna

format Ciąg argumentu przekazanego do metody, takie jak WriteLine, Write, lub String.Format nie zawiera element format, który odpowiada każdego argumentu obiektu lub na odwrót.

Opis reguły

Argumenty metod, takich jak WriteLine, Write, i Format składają się z ciągu formatu następuje kilka System.Object wystąpień.Ciąg formatu składa się z tekstu i elementów osadzonych format formularza {index [, wyrównanie] [: formatString]}. 'Indeks ' jest całkowitą względem zera, który wskazuje, które obiekty do sformatowania.Jeśli obiekt nie ma odpowiedniego indeksu w ciągu formatu, obiekt zostanie zignorowany.Jeśli określony przez "index" obiekt nie istnieje, System.FormatException jest generowane w czasie wykonywania.

Jak naprawić naruszenia

Aby naprawić naruszenie tej zasady, zapewniają element formatu dla każdego argumentu obiektu i podać argument obiektu dla każdego elementu format.

Kiedy do pomijania ostrzeżenia

Nie pomijaj ostrzeżenie od tej reguły.

Przykład

W poniższym przykładzie przedstawiono dwa naruszenia reguły.

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));
      }
   }
}