首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

如何判斷字串是否為空字串(一):三種寫法與原始碼探討

     編輯:關於C語言

緣起於 FxCop 建議使用 string.Length 判斷空字串,本文探討背後原因。

三種常用判空寫法

  • Length 法:bool isEmpty = (str.Length == 0);
  • Empty 法:bool isEmpty = (str == String.Empty);
  • General 法:bool isEmpty = (str == "");

深入 .NET 內部實作

透過 Reflector 反編譯 System.String 原始碼片段:

public sealed class String : IComparable, ICloneable, ... {
 static String() { string.Empty = ""; }
 public static readonly string Empty;
 public static bool Operator ==(string a, string b) { return string.Equals(a, b); }
 public static bool Equals(string a, string b) {
   if (a == b) return true;
   if ((a != null) && (b != null)) return string.EqualsHelper(a, b);
   return false;
 }
 private static unsafe bool EqualsHelper(string ao, string bo) {
   int num1 = ao.Length;
   if (num1 != bo.Length) return false;
   // 逐字元比較...
 }
 private extern int InternalLength();
 public int Length { get { return this.InternalLength(); } }
}

Rotor 版本類似,但無 EqualsHelper,改用 public extern bool Equals(String value);。

下篇將詳細比較三種寫法的效能差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved