CA2249: Zvažte použití string.Contains místo String.IndexOf

Vlastnost Hodnota
ID pravidla CA2249
Název Zvážit možnost místo string.IndexOf použít string.Contains
Kategorie Využití
Oprava způsobující chybu nebo chybu způsobující chybu Nenarušující
Povoleno ve výchozím nastavení v .NET 8 Jako návrh

Příčina

Toto pravidlo vyhledá volání, ve IndexOf kterých se výsledek používá ke kontrole přítomnosti nebo nepřítomnosti podřetězce, a místo toho navrhuje použití Contains ke zlepšení čitelnosti.

Popis pravidla

Pokud IndexOf se používá ke kontrole, jestli je výsledek roven -1 nebo větší nebo roven, 0může být volání bezpečně nahrazeno Contains bez dopadu na výkon.

V závislosti na IndexOf použitém přetížení by navrhovaná oprava mohla získat přidaný comparisonType argument:

Přetížení Navrhovaná oprava
String.IndexOf(char) String.Contains(char)
String.IndexOf(string) String.Contains(string, StringComparison.CurrentCulture)
String.IndexOf(char, StringComparison.Ordinal) String.Contains(char)
String.IndexOf(string, StringComparison.Ordinal) String.Contains(string)
String.IndexOf(char, NON StringComparison.Ordinal)* String.Contains(char, NON StringComparison.Ordinal)*
String.IndexOf(string, NON StringComparison.Ordinal)* String.Contains(string, NON StringComparison.Ordinal)*

* Jakákoli StringComparison jiná hodnota výčtu než StringComparison.Ordinal:

Jak opravit porušení

Porušení může být buď opraveno ručně, nebo v některých případech pomocí rychlých akcí opravit kód v sadě Visual Studio.

Příklady

Následující dva fragmenty kódu ukazují všechna možná porušení pravidla v jazyce C# a postup jejich opravy:

using System;

class MyClass
{
    void MyMethod()
    {
        string str = "My text";
        bool found;

        // No comparisonType in char overload, so no comparisonType added in resulting fix
        found = str.IndexOf('x') == -1;
        found = str.IndexOf('x') >= 0;

        // No comparisonType in string overload, adds StringComparison.CurrentCulture to resulting fix
        found = str.IndexOf("text") == -1;
        found = str.IndexOf("text") >= 0;

        // comparisonType equal to StringComparison.Ordinal, removes the argument
        found = str.IndexOf('x', StringComparison.Ordinal) == -1;
        found = str.IndexOf('x', StringComparison.Ordinal) >= 0;

        found = str.IndexOf("text", StringComparison.Ordinal) == -1;
        found = str.IndexOf("text", StringComparison.Ordinal) >= 0;

        // comparisonType different than StringComparison.Ordinal, preserves the argument
        found = str.IndexOf('x', StringComparison.OrdinalIgnoreCase) == -1;
        found = str.IndexOf('x', StringComparison.CurrentCulture) >= 0;

        found = str.IndexOf("text", StringComparison.InvariantCultureIgnoreCase) == -1;
        found = str.IndexOf("text", StringComparison.InvariantCulture) >= 0;

        // Suggestion message provided, but no automatic fix offered, must be fixed manually
        int index = str.IndexOf("text");
        if (index == -1)
        {
            Console.WriteLine("'text' Not found.");
        }
    }
}
using System;

class MyClass
{
    void MyMethod()
    {
        string str = "My text";
        bool found;

        // No comparisonType in char overload, so no comparisonType added in resulting fix
        found = !str.Contains('x');
        found = str.Contains('x');

        // No comparisonType in string overload, adds StringComparison.CurrentCulture to resulting fix
        found = !string.Contains("text", StringComparison.CurrentCulture);
        found = string.Contains("text", StringComparison.CurrentCulture);

        // comparisonType equal to StringComparison.Ordinal, removes the argument
        found = !string.Contains('x');
        found = string.Contains('x');

        found = !string.Contains("text");
        found = string.Contains("text");

        // comparisonType different than StringComparison.Ordinal, preserves the argument
        ;found = !string.Contains('x', StringComparison.OrdinalIgnoreCase)
        found = string.Contains('x', StringComparison.CurrentCulture);

        found = !string.Contains("text", StringComparison.InvariantCultureIgnoreCase);
        found = string.Contains("text", StringComparison.InvariantCulture);

        // This case had to be manually fixed
        if (!str.Contains("text"))
        {
            Console.WriteLine("'text' Not found.");
        }
    }
}

Tip

Oprava kódu je k dispozici pro toto pravidlo v sadě Visual Studio. Pokud ho chcete použít, umístěte kurzor na porušení a stiskněte ctrl+. (tečka). Zvolte Možnost Zvážit použití řetězce. Obsahuje místo řetězce řetězec. IndexOf ze seznamu zobrazených možností

Code fix for CA2249 - Consider using 'string.Contains' instead of 'string.IndexOf'

Kdy potlačit upozornění

Pokud zlepšení čitelnosti kódu není problém, je bezpečné potlačit porušení tohoto pravidla.

Potlačení upozornění

Pokud chcete pouze potlačit jedno porušení, přidejte do zdrojového souboru direktivy preprocesoru, abyste pravidlo zakázali a znovu povolili.

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

Pokud chcete pravidlo pro soubor, složku nebo projekt zakázat, nastavte jeho závažnost v none konfiguračním souboru.

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

Další informace naleznete v tématu Jak potlačit upozornění analýzy kódu.

Viz také