如何返回 Generic T.ToString()

本文关键字:Generic ToString 返回 何返回 | 更新日期: 2023-09-27 18:34:11

给定这样的定义

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
    }
}

如何覆盖 ToString() 并返回 V.ToString();

如何返回 Generic T.ToString()

好吧,看起来你想使用:

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
    }
}

为什么?因为您在任何地方都没有 T,并且 K/V 是类型,而不是类型的实例。