CA1820:應該使用字串長度測試空白字串

屬性
規則識別碼 CA1820
職稱 應該使用字串長度測試空白字串
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

字串會使用 Object.Equals來比較空字串。

檔案描述

使用 String.Length 屬性或 String.IsNullOrEmpty 方法比較字串的速度比使用 Equals快。 這是因為 Equals 執行的 CIL 指令明顯大於 IsNullOrEmpty 或執行以擷取 Length 屬性值的指令數目,並將其與零進行比較。

若為 Null 字串, Equals<string>.Length == 0 行為方式不同。 如果您嘗試在 Null 字串上取得 屬性的值 Length ,Common Language Runtime 會 System.NullReferenceException擲回 。 如果您在 Null 字串與空字串之間執行比較,Common Language Runtime 不會擲回例外狀況並傳 false回 。 針對 Null 進行測試並不會影響這兩種方法的相對效能。 以 .NET Framework 2.0 或更新版本為目標時,請使用 IsNullOrEmpty 方法。 否則,請盡可能使用 Length == 0 比較。

如何修正違規

若要修正此規則的違規,請變更比較以使用 IsNullOrEmpty 方法。

隱藏警告的時機

如果效能不是問題,請務必隱藏此規則的警告。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

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

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

範例

下列範例說明用來尋找空字串的不同技術。

public class StringTester
{
    string s1 = "test";

    public void EqualsTest()
    {
        // Violates rule: TestForEmptyStringsUsingStringLength.
        if (s1 == "")
        {
            Console.WriteLine("s1 equals empty string.");
        }
    }

    // Use for .NET Framework 1.0 and 1.1.
    public void LengthTest()
    {
        // Satisfies rule: TestForEmptyStringsUsingStringLength.
        if (s1 != null && s1.Length == 0)
        {
            Console.WriteLine("s1.Length == 0.");
        }
    }

    // Use for .NET Framework 2.0.
    public void NullOrEmptyTest()
    {
        // Satisfies rule: TestForEmptyStringsUsingStringLength.
        if (!String.IsNullOrEmpty(s1))
        {
            Console.WriteLine("s1 != null and s1.Length != 0.");
        }
    }
}