2012-12-13 27 views
4

我正在通過System.String尋找,我想知道爲什麼EndsWithStartsWith方法在參數方面不對稱。爲什麼System.String.EndsWith()有一個char重載並且System.String.StartsWith()沒有?

具體來說,爲什麼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) 

回答

5

展望ILSpy,此重載似乎壓倒多數的IO代碼被稱爲

s.EndsWith(Path.DirectorySeparatorChar) 

想必這只是一些C#團隊決定這將是必須避免重複的代碼是有用的。

需要注意的是,它更容易使這個檢查在啓動(s[0] == c VS s[s.Length - 1] == c),這也可以解釋爲什麼他們沒有刻意做出StartsWith超載。

+0

的'StartsWith'答案是有道理的。我不確定這個答案的第一部分是否對我有意義 - 當我使用dotPeek時,我實際上得到了上面的輸出。在Path.DirectorySeparatorChar中調用'EndsWith'passing是什麼意思? –

+1

我的意思是......看起來好像編寫IO代碼的人注意到他們需要檢查字符串的最後一個字符,所以他們只寫了一個'internal'輔助方法來使它更容易? – Rawling

+0

我現在明白了 - 結合下面的答案是有道理的。我想知道爲什麼ILSpy顯示的代碼與dotPeek不同? –

3

這是僅在以下8種方法中使用的在mscorlib一個內部方法:

  • System.Security.Util.StringExpressionSet.CanonicalizePath(串 路徑,布爾needFullPath):串
  • 系統.IO.IsolatedStorage.IsolatedStorageFile.DirectoryExists(串 路徑):布爾
  • System.IO.Directory.GetDemandDir(串FULLPATH,布爾thisDirOnly):串
  • System.IO.Director yInfo.GetDirName(字符串FULLPATH):串
  • System.Security.Util.URLString.IsRelativeFileUrl:布爾
  • System.IO.DirectoryInfo.MoveTo(字符串destDirName):無效
  • System.IO.DirectoryInfo.Parent: DirectoryInfo的
  • System.Globalization.CultureData.SENGDISPLAYNAME:字符串

也許只是爲了方便和代碼重用:)

相關問題