为什么System.String.EndsWith()有一个char重载而System.String.StartsWith()没有?

时间:2012-12-13 15:12:36

标签: c# .net string char

我正在浏览System.String,我想知道为什么EndsWithStartsWith方法在参数方面不对称。

具体来说,为什么System.String.EndsWith支持char参数而System.String.StartsWith不支持?{1}}?这是因为任何限制或设计特征吗?

// 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)

2 个答案:

答案 0 :(得分:5)

查看ILSpy,这个重载似乎绝大多数都是在IO代码中调用的

s.EndsWith(Path.DirectorySeparatorChar)

据推测,这只是C#团队认为必须避免重复代码有用的事情。

请注意,在开始时(s[0] == c vs s[s.Length - 1] == c)进行此检查要容易得多,这也可以解释为什么他们不打算使StartsWith超载。

答案 1 :(得分:3)

这是一种内部方法,仅用于mscorlib中的以下8种方法:

  • System.Security.Util.StringExpressionSet.CanonicalizePath(串 path,bool needFullPath):string
  • System.IO.IsolatedStorage.IsolatedStorageFile.DirectoryExists(串 路径):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:字符串

可能只是为了方便和代码重用:)