如何返回 Generic T 的 ToString() 方法

3

假设有如下定义:

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();
1个回答

11

看起来您想要使用:

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是类型,不是类型的实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接