如何实现Tuple. create(T1 item1, T2 item2)

本文关键字:T1 T2 create item1 item2 何实现 Tuple 实现 | 更新日期: 2023-09-27 18:05:57

我试图实现与Tuple<T1,T2>.Create<T1,T2>(T1 item1, T2 item2)类似的方法,但我仍然必须指定类型参数,而Tuple。

我认为这个定义是正确的。我做错了什么?下面是我的代码:
public class KeyValuePair<K, V>
{
    public K Key { get; set; }       
    public V Value { get; set; }
    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V> { Key = key, Value = value };
    }
}

如何实现Tuple<T1,T2>. create<T1,T2>(T1 item1, T2 item2)

您需要创建类的非泛型版本。

public class KeyValuePair
{
    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V>(key, value);
    }
}

我明白了。它不是在Tuple<T1,T2>类上定义为静态方法,而是在Tuple类上定义为静态方法。