Delen via


CA2249: Overweeg het gebruik van String.Contains in plaats van String.IndexOf

Eigendom Waarde
Regel-id CA2249
Titel Overweeg het gebruik van String.Contains in plaats van String.IndexOf
Categorie Gebruik
Oplossing is brekend of niet-brekend Niet-brekend
Standaard ingeschakeld in .NET 9 Als suggestie

Oorzaak

Deze regel zoekt aanroepen van IndexOf waar het resultaat wordt gebruikt om te controleren op de aanwezigheid of afwezigheid van een subtekenreeks, en stelt voor om Contains in plaats daarvan te gebruiken, om de leesbaarheid te verbeteren.

Beschrijving van regel

Wanneer IndexOf wordt gebruikt om te controleren of het resultaat gelijk is aan of groter of gelijk -1is aan0, kan de aanroep veilig worden vervangen door Contains zonder dat dit invloed heeft op de prestaties.

Afhankelijk van de IndexOf gebruikte overbelasting kan de voorgestelde oplossing een comparisonType argument toevoegen:

Overbelasting Voorgestelde oplossing
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)*

* Elke opsommingswaarde StringComparison anders dan StringComparison.Ordinal:

Hoe schendingen op te lossen

De schending kan handmatig worden opgelost, of in sommige gevallen met snelle acties om code in Visual Studio op te lossen.

Voorbeelden

In de volgende twee codefragmenten ziet u alle mogelijke schendingen van de regel in C# en hoe u deze kunt oplossen:

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 = !str.Contains("text", StringComparison.CurrentCulture);
        found = str.Contains("text", StringComparison.CurrentCulture);

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

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

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

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

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

Aanbeveling

Er is een codeoplossing beschikbaar voor deze regel in Visual Studio. Als u het wilt gebruiken, plaatst u de cursor op de overtreding en drukt u op Ctrl+. (punt). Kies de optie Overweeg 'string.Contains' te gebruiken in plaats van 'string.IndexOf' uit de lijst met opties die wordt gepresenteerd.

Codefix voor CA2249 - Overweeg om 'string.Contains' te gebruiken in plaats van 'string.IndexOf'

Wanneer waarschuwingen onderdrukken

Het is veilig om een schending van deze regel te onderdrukken als het verbeteren van de leesbaarheid van code geen probleem is.

Een waarschuwing onderdrukken

Als u slechts één schending wilt onderdrukken, voegt u preprocessorrichtlijnen toe aan uw bronbestand om de regel uit te schakelen en vervolgens opnieuw in te schakelen.

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

Als u de regel voor een bestand, map of project wilt uitschakelen, stelt u de ernst none ervan in op het configuratiebestand.

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

Zie Hoe u codeanalysewaarschuwingen kunt onderdrukken voor meer informatie.

Zie ook