且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 string.Substring(char, char) 代替 string.Substring(int, int)?

更新时间:2022-06-22 02:42:03

有没有办法强制解释器不要将字符转换为 int?

Is there a way to force the interpreter not to do the cast char to int?

没有.当遇到针对目标表达式执行的方法调用时,编译器首先检查目标声明类型上的任何实例方法是否与参数兼容.如果没有兼容的方法,它只查找扩展方法.

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) 兼容,因为 的隐式转换charint.

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.