我编写了以下扩展方法来覆盖NameValueCollection.ToString
public static string ToString(this NameValueCollection a)
{
return string.Join("&", a.AllKeys.Select(k => $"{k}={a[k]}"));
}但是它仍然使用默认的ToString方法。
当我添加override关键字时,会得到一个错误:
'ToString(NameValueCollection)':没有找到合适的重写方法
当我添加new关键字时,它说不需要new关键字:
“ToString(NameValueCollection)”不隐藏继承的成员。新关键字不是必需的。
发布于 2016-10-30 22:33:07
如果要为ToString()重写NameValueCollection,则需要创建继承NameValueCollection的新对象
public class CustomNameValueCollection:NameValueCollection
{
public override String ToString()
{
return string.Join("&", AllKeys.Select(k => $"{k}={this[k]}"));
}
}在新的CustomValueCollection中填充集合,然后调用ToString()。
CustomValueCollection coll = new CustomValueCollection();
coll.Add("key", "value");
string collString = coll.ToString();https://stackoverflow.com/questions/40334219
复制相似问题