为什么会发生这种情况?请注意下面的代码:使用扩展方法时发生意外的行为
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#中的错误?
P.S.我使用VS2010。
不确定是否更好地使用副本替换字符串本身是个好主意。 – rekire 2012-02-10 23:25:26