簡體   English   中英

為什么System.String.EndsWith()有一個char重載而System.String.StartsWith()沒有?

[英]Why does System.String.EndsWith() have a a char overload and System.String.StartsWith() does not?

我正在查看System.String ,我想知道為什么EndsWithStartsWith方法在它們可以采用的參數方面不對稱。

具體來說,為什么System.String.EndsWith支持char參數而System.String.StartsWith不支持? 這是因為任何限制或設計特征嗎?

// System.String.EndsWith method signatures
[__DynamicallyInvokable]
public bool EndsWith(string value)

[ComVisible(false)]
[SecuritySafeCritical]
[__DynamicallyInvokable]
public bool EndsWith(string value, StringComparison comparisonType)

public bool EndsWith(string value, bool ignoreCase, CultureInfo culture)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
internal bool EndsWith(char value)
{
  int length = this.Length;
  return length != 0 && (int) this[length - 1] == (int) value;
}

// System.String.StartsWith method signatures
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
[__DynamicallyInvokable]
public bool StartsWith(string value)

[SecuritySafeCritical]
[ComVisible(false)]
[__DynamicallyInvokable]
public bool StartsWith(string value, StringComparison comparisonType)

public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)

看看ILSpy,這個重載似乎壓倒性地在IO代碼中調用

s.EndsWith(Path.DirectorySeparatorChar)

據推測,這只是C#團隊認為必須避免重復代碼有用的東西。

請注意,在開始時進行此檢查要容易得多( s[0] == c vs s[s.Length - 1] == c ),這也可以解釋為什么他們不打算使StartsWith超載。

這是一個內部方法,僅用於mscorlib中的以下8個方法:

  • System.Security.Util.StringExpressionSet.CanonicalizePath(string path,bool needFullPath):string
  • System.IO.IsolatedStorage.IsolatedStorageFile.DirectoryExists(string path):bool
  • System.IO.Directory.GetDemandDir(string fullPath,bool thisDirOnly):string
  • System.IO.DirectoryInfo.GetDirName(string fullPath):string
  • System.Security.Util.URLString.IsRelativeFileUrl:布爾
  • System.IO.DirectoryInfo.MoveTo(string destDirName):void
  • System.IO.DirectoryInfo.Parent:DirectoryInfo的
  • System.Globalization.CultureData.SENGDISPLAYNAME:字符串

可能只是為了方便和代碼重用:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM