【问题标题】:How is Tuple<T1,T2>.Create<T1,T2>(T1 item1, T2 item2) implemented?Tuple<T1,T2>.Create<T1,T2>(T1 item1, T2 item2) 是如何实现的?
【发布时间】:2011-08-18 20:53:19
【问题描述】:

我正在尝试实现与Tuple&lt;T1,T2&gt;.Create&lt;T1,T2&gt;(T1 item1, T2 item2) 类似的方法,但我仍然需要指定类型参数,而 Tuple.Create 会推断它们。

我认为这个定义是正确的。我究竟做错了什么?这是我的代码:

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

【问题讨论】:

    标签: c# .net generics tuples


    【解决方案1】:

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

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

    【讨论】:

    • Key 和 Value 属性是只读的,这意味着 kvp 是不可变的。我做了相关的编辑。
    【解决方案2】:

    我想通了。它不是在Tuple&lt;T1,T2&gt; 类上定义为静态方法,而是在 Tuple 类上。

    【讨论】:

    • @Quintin - 谢谢!我没有意识到存在处女耳朵。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多