如何返回Generic T.ToString()

Kum*_*mar 2 .net c# generics

给出这样的定义

public class KeyValueItem<K,V>
{
    public K Key { get; set; }
    public V Value { get; set; }

    public override string ToString()
    {
        return T.ToString(); // does not compile
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何重写ToString()并返回V.ToString();

Bru*_*ner 10

好吧,看起来你想要使用:

public class KeyValueItem<K,V>
{
    public K Key { get; set; }
    public V Value { get; set; }

    public override string ToString()
    {
        return this.Value.ToString(); // does compile
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么?因为你没有任何地方的T和K/V是类型,而不是类型的实例.