Ale*_*der 6 c# extension-methods substring visual-studio-2010
我做了扩展方法,它在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
?
Substring2
),则所有方法均有效。chars
为params char[]
,则无法正常运行,如果我像params一样调用它,但是当然可以像数组一样运行。"M(234:342);".Substring('(', ')')
不会引发任何编译错误,但仍会引发异常。chars
为strings
扩展方法,它也可以工作。这是我目前最喜欢的解决方案- 与检查输入字符串的长度结合Substring(char, char)
使用Substring(string, string)
。Jon*_*eet 12
有没有一种方法可以强制解释器不要将强制转换为int类型的字符?
否。当遇到针对目标表达式执行的方法调用时,编译器首先检查目标声明类型上的任何实例方法是否与参数兼容。如果没有兼容的方法,它将仅查找扩展方法。
在您的情况下,由于从到的隐式转换,常规string.Substring(int, int)
方法与参数兼容。(char, char)
char
int
The simplest solution is to rename your extension method - something like SubstringBetween
perhaps.
归档时间: |
|
查看次数: |
191 次 |
最近记录: |