2012-12-13 28 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:字符串

也许只是为了方便和代码重用:)

相关问题