C# 为什么System.String.EndsWith()有字符重载而System.String.StartWith()没有?
我查看了C# 为什么System.String.EndsWith()有字符重载而System.String.StartWith()没有?,c#,.net,string,char,C#,.net,String,Char,我查看了System.String,我想知道为什么EndsWith和StartsWith方法在参数上是不对称的 具体来说,为什么System.String.EndsWith支持char参数,而System.String.StartsWith不支持char参数?这是因为任何限制或设计特点吗 // System.String.EndsWith method signatures [__DynamicallyInvokable] public bool EndsWith(string value)
System.String
,我想知道为什么EndsWith
和StartsWith
方法在参数上是不对称的
具体来说,为什么System.String.EndsWith
支持char参数,而System.String.StartsWith
不支持char参数?这是因为任何限制或设计特点吗
// 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
vss[s.Length-1]==c
),这也可能解释了为什么他们没有费心使用重载启动。这是一种内部方法,仅在mscorlib
中的以下8种方法中使用:
- System.Security.Util.StringExpressionSet.CanonicalizePath(字符串
路径,bool needFullPath):字符串
- System.IO.IsolatedStorage.IsolatedStorageFile.DirectoryExists(字符串
路径:布尔
- System.IO.Directory.GetDemandDir(字符串完整路径,bool thisdireOnly):字符串
- System.IO.DirectoryInfo.GetDirName(字符串完整路径):字符串
- System.Security.Util.URLString.IsRelativeFileUrl:bool
- System.IO.DirectoryInfo.MoveTo(字符串destDirName):无效
- System.IO.DirectoryInfo.Parent:DirectoryInfo
- System.Globalization.CultureData.SENGDISPLAYNAME:string
可能只是为了方便和代码重用:)答案的StartsWith
是有意义的。我不确定这个答案的第一部分对我是否有意义——当我使用dotPeek时,我实际上得到了上面的输出。调用EndsWith
传入Path.directoryseportorchar
意味着什么?我的意思是。。。似乎编写IO代码的人注意到他们需要经常检查字符串的最后一个字符,所以他们只编写了一个internal
helper方法来简化它?我现在明白了-结合下面的答案,这是有意义的。我想知道为什么ILSpy显示的代码与dotPeek不同?在ILSpy中,它允许您搜索使用方法的位置-我的代码片段是此方法通常的调用方式(尽管在其他位置使用'*'
或':'
调用)。