问题描述
我制作了返回leftChar
和rightChar
之间的字符串的扩展方法:
I made the extension method that returns a string between leftChar
and 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;
}
当我像这样调用它时:
string str = "M(234:342);".Substring('(', ')');
我收到异常:
System.ArgumentOutOfRangeException: startIndex не может быть больше,чем длина строки.注释:startIndex вSystem.String.Substring(Int32 startIndex, Int32 length)
扩展方法的命名空间和调用代码是正确的.IntelliSense 向我推荐了 3 种扩展方法(两种基本方法和一种我的方法).
The namespace of the extension method and the invoking code is correct. IntelliSense suggest me 3 extension methods (two basic and one mine).
(extension) string string.Substring(char leftChar, char rightChar)
很明显 string.Substring(int startIndex, int Length)
与我的扩展方法重叠,因为编译器自动将 char 转换为 int.
It is clear that string.Substring(int startIndex, int Length)
overlaps with my extension method because the compiler casts char to int automaticaly.
有没有办法强制编译器不将 char
强制转换为 int
?
Is there a way to force the compiler not to do the cast char
to int
?
- 如果我重命名扩展方法(如
Substring2
),一切正常. - 如果我将
chars
更改为params char[]
,它不起作用,如果我像 params 一样调用它,但当然像数组一样工作. - 如果我删除扩展方法,
"M(234:342);".Substring('(', ')')
不会抛出任何编译错误,但仍会抛出异常. - 如果我在扩展方法中将
chars
更改为strings
它也可以工作.对于这个问题,这是我目前最喜欢的解决方案 - 将我的Substring(char, char)
与Substring(string, string)
结合起来,并检查输入字符串的长度.
- If I rename the extension method (like
Substring2
) all works. - If I change
chars
toparams char[]
, it does not work, if I invoke it like params, but of course works like array. - If I delete the extension method,
"M(234:342);".Substring('(', ')')
does not throw any compilation error, but still throw the exception. - If I change
chars
tostrings
in the extension method it also works. This is my current favorite solution for this issue - to combine mySubstring(char, char)
withSubstring(string, string)
with checking lengths of input strings.
推荐答案
没有.当遇到针对目标表达式执行的方法调用时,编译器首先检查目标声明类型上的任何实例方法是否与参数兼容.如果没有兼容的方法,它只查找扩展方法.
No. When it encounters a method invocation executed against a target expression, the compiler first checks whether any instance methods on the target's declared type are compatible with the arguments. It only looks for extension methods if there are no compatible methods.
在您的情况下,常规 string.Substring(int, int)
方法与参数 (char, char)
兼容,因为 的隐式转换char
到 int
.
In your case, the regular string.Substring(int, int)
method is compatible with arguments (char, char)
because of the implicit conversion from char
to int
.
最简单的解决方案是重命名您的扩展方法 - 可能类似于 SubstringBetween
.
The simplest solution is to rename your extension method - something like SubstringBetween
perhaps.
这篇关于如何使用 string.Substring(char, char) 代替 string.Substring(int, int)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!