共用方式為


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

型別名稱

TestForEmptyStringsUsingStringLength

CheckId

CA1820

分類

Microsoft.Performance

中斷變更

中斷

原因

使用 Object.Equals 比較字串與空字串。

規則描述

使用 String.Length 屬性或 String.IsNullOrEmpty 方法比較字串,明顯地會比使用 Equals 還快。 這是因為 Equals 所執行的 MSIL 指令數目,明顯地比 IsNullOrEmpty,或擷取 Length 屬性值再與零相比所執行的指令數目更多。

您應該注意 EqualsLength == 0 在處理 null 字串時有所不同。 如果您嘗試取得 null 字串的 Length 屬性值,則 Common Language Runtime 會擲回 System.NullReferenceException。 如果您在 null 字串與空字串之間執行比較,則 Common Language Runtime 並不會擲回例外狀況 (Exception),而是傳回 false。 進行 null 測試並不會明顯影響這兩種方法的相對效能。 以 .NET Framework 2.0 為目標時,請使用 IsNullOrEmpty 方法。 否則,請盡量使用 Length == 比較。

如何修正違規

若要修正此規則的違規情形,請將比較變更為使用 Length 屬性,並測試 null 字串。 以 .NET Framework 2.0 為目標時,請使用 IsNullOrEmpty 方法。

隱藏警告的時機

如果效能不是問題,則您可以放心地隱藏這項規則的警告。

範例

下列範例會說明用以尋找空字串的不同技巧。

using System;

namespace PerformanceLibrary
{
   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.");
         }
      }
   }
}