Overriding ToString () on KeyValuePair <> struct

As in the tile: overriding ToString () on KeyValuePair <> struct (System.Collections.Generic). I am wondering if this can be done at all in C # (sealed structures).

Can someone give some ideas or alternative approaches?

Or just I have to forget to override and move on to the following:

class MyKeyValuePair
{
    public KeyValuePair<T> Pair { get; set; }
    public MyKeyValuePair(KeyValuePair<T> pair)
    {
        this.Pair = pair;
    }
    public override ToString()
    {
        ...
    }
}
+3
source share
4 answers

No.

You cannot modify existing types, but structcannot be inherited.

+5
source

How about this:

static class KeyValueHelper
{
   public static string ToMyString<K, V>(this KeyValuePair<K, V> pair) { ... }
}
+2
source

A struct , .

, .

+1

, , , :

static class KeyValuePairMethods
{

    public static String ToCustomString<TK, TV>(this KeyValuePair<TK, TV> kvp)
    {
        return String.Format("{0}: {1}", kvp.Key, kvp.Value);
    }
}

:

new KeyValuePair<string, int>("Hello", 12).ToCustomString();

From the external course course, the ToString () method will still be used, so this probably will not bring you anything.

+1
source

All Articles