繁体   English   中英

重写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)':找不到合适的方法来覆盖

当我添加new关键字时,它说不需要new关键字:

'ToString(NameValueCollection)'不隐藏继承的成员。 不需要new关键字。

如果你想覆盖的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM