覆盖 NameValueCollection ToString
Overriding NameValueCollection ToString
我已经编写了以下扩展方法来覆盖 NameValueCollection.ToString
:
public static string ToString(this NameValueCollection a)
{
return string.Join("&", a.AllKeys.Select(k => $"{k}={a[k]}"));
}
但它仍然使用默认的ToString
方法。
当我添加 override
关键字时出现错误:
'ToString(NameValueCollection)': no suitable method found to override
当我添加 new
关键字时,它说不需要 new
关键字:
'ToString(NameValueCollection)' does not hide an inherited member. The new keyword is not required.
如果要为 NameValueCollection
覆盖 ToString(),您需要创建一个继承 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();
我已经编写了以下扩展方法来覆盖 NameValueCollection.ToString
:
public static string ToString(this NameValueCollection a)
{
return string.Join("&", a.AllKeys.Select(k => $"{k}={a[k]}"));
}
但它仍然使用默认的ToString
方法。
当我添加 override
关键字时出现错误:
'ToString(NameValueCollection)': no suitable method found to override
当我添加 new
关键字时,它说不需要 new
关键字:
'ToString(NameValueCollection)' does not hide an inherited member. The new keyword is not required.
如果要为 NameValueCollection
覆盖 ToString(),您需要创建一个继承 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();