我做了扩展方法,它在leftChar和之间返回一个字符串rightChar:
public static string Substring(this string This, char leftChar, char rightChar)
{
int i_left = This.IndexOf(leftChar);
if (i_left >= 0)
{
int i_right = This.IndexOf(rightChar, i_left);
if (i_right >= i_left)
{
return This.Substring(i_left + 1, i_right - i_left - 1);
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
当我这样调用它时:
string str = "M(234:342);".Substring('(', ')');
Run Code Online (Sandbox Code Playgroud)
我得到例外:
System.ArgumentOutOfRangeException:startIndex ?? ?????? ???? ??????,??? ?????? ?????? ??? ?????????:startIndex?System.String.Substring(Int32 startIndex,Int32长度)
扩展方法和调用代码的名称空间正确。IntelliSense建议我3种扩展方法(两种基本方法和一种方法)。
(扩展名)字符串string.Substring(char leftChar,char rightChar)
显然,这string.Substring(int startIndex, int Length)与我的扩展方法重叠,因为编译器会自动将char强制转换为int。
有没有办法强迫编译器不执行强制char转换int …