为什么会出现这种情况?请遵守以下代码:
static class StringExtension
{
public static string Remove(this string s, char c)
{
return s.Replace(c.ToString(), "");
}
public static string Remove(this string s, char[] a)
{
foreach (char c in a)
{
s = s.Remove((char)c); // <---- ArgumentOutOfRange Exception here
}
return s;
}
}
class Program
{
static void Main(string[] args)
{
char[] a = new char[] { '.', ',' };
string testString = "Clean.this,string.from,periods.and,commas.";
Console.WriteLine(testString.Remove(a));
}
}
当我运行此代码时,我在指示行收到 ArgumentOutOfRange 异常。事实证明,即使我有扩展名 Remove (this, char) 的特定代码,并且我明确(尽管应该没有理由)指定参数的类型,它也会忽略我的扩展名并尝试调用原始的 Remove( int) 方法。
是我做错了什么还是这是 C# 中的错误?
附:我用的是VS2010。
这行:
s.Remove((char) c);
正在打电话string.Remove(int) http://msdn.microsoft.com/en-us/library/system.string.remove.aspx- 如果可以的话,编译器将始终使用适用的实例方法而不是扩展方法。它适用于从隐式转换char
to int
。这就是抛出异常的方法,因为您传递给它的参数超出了范围。 (事实上,你很幸运 - 在更糟糕的情况下,它会in范围,并返回完全意想不到的结果。)
一般来说我会strongly建议您不要创建与扩展类型上的实例方法同名的扩展方法,特别如果他们有相同数量的参数。一般来说,如果不添加扩展方法,解决重载问题就已经足够困难了。不要忘记,无论何时you如果你无法轻易地弄清楚你的代码在做什么,那么在一年内阅读代码的人将会面临十倍困难的工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)