【发布时间】:2021-05-15 11:53:26
【问题描述】:
我为string编写了一个带有非常简单扩展方法的.DLL库。
我的方法 - .Remove(char deletedChar),删除 string 中所有出现的 char。这会重载默认的 .Remove(int startIndex) 方法。但是,当我想使用它时,会调用.Remove(int startIndex),而不是我的方法,尽管我将char 作为参数。
我的意思是,给定这段代码:
string Test = "12-34-56-78-90-123-456-789-0123-4567-89012-34567-890123-456789-000000";
MessageBox.Show(Test.Remove('-'));
我的预期结果是:
1234567890123456789012345678901234567890123456789000000
但是,实际结果是:
12-34-56-78-90-123-456-789-0123-4567-89012-34
查看截图:
这意味着,我的char '-' 被解释为它的 ASCII 值 (45),这是删除字符串的起始索引。
为什么会这样?即使将char 转换为char(即(char)'-')也无法修复它。我知道我可以简单地重命名扩展方法,但我仍然不明白为什么会发生这种情况。有人可以解释这种现象或指出解释它的文档吗?
粘贴我的扩展方法以防有人想要使用它:
/// <summary>
/// Removes all occurences of specified char.
/// </summary>
/// <param name="str"></param>
/// <param name="deletedChar">The char you want to remove.</param>
/// <returns>string without the specified char.</returns>
public static string Remove(this string str, char deletedChar)
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] == deletedChar)
{
str = str.Remove(i, 1);
i--;
}
}
return str;
}
【问题讨论】:
标签: c# dll extension-methods