2016-10-30 3 views
0

J'ai écrit la méthode d'extension suivante pour remplacer le NameValueCollection.ToString:Redéfinition NameValueCollection ToString

public static string ToString(this NameValueCollection a) 
{ 
    return string.Join("&", a.AllKeys.Select(k => $"{k}={a[k]}")); 
} 

Mais il utilise toujours la méthode par défaut ToString.

Quand j'ajouter le mot-clé override je reçois une erreur:

'ToString(NameValueCollection)': no suitable method found to override

Et quand j'ajoute new mot-clé, il dit ce mot-clé new n'est pas nécessaire:

'ToString(NameValueCollection)' does not hide an inherited member. The new keyword is not required.

Répondre

1

Si vous souhaitez remplacer ToString() pour NameValueCollection, vous devez créer un nouvel objet qui hérite NameValueCollection

public class CustomNameValueCollection:NameValueCollection 
{ 
    public override String ToString() 
    { 
     return string.Join("&", AllKeys.Select(k => $"{k}={this[k]}")); 
    } 
} 

Vous remplissez votre collection dans votre nouvelle CustomValueCollection et vous pouvez appeler ToString().

CustomValueCollection coll = new CustomValueCollection(); 
coll.Add("key", "value"); 

string collString = coll.ToString(); 
+0

Eh bien, j'espérais changer la méthode par défaut, mais cela semble être la seule solution. Merci beaucoup. –