我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。

谢谢你!


当前回答

元组从。net 4.0开始就可用了,并且支持泛型:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

在以前的版本中,您可以使用System.Collections.Generic。KeyValuePair<K, V>或如下解:

public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};

像这样使用它:

Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

这个输出:

test
2

或者甚至是这个链对:

Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);

输出:

test
12
true

其他回答

我刚刚问了同样的问题,在快速谷歌之后,我发现。net中有一个pair类,除了它在System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) 天知道他们为什么把它放在那里而不是集合框架

c#在4.0版就有了元组。

从。net 4.0开始,你有了System。元组<T1, T2>类:

// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);

根据您想要实现的目标,您可能想尝试KeyValuePair。

不能更改条目的键当然可以通过简单地用KeyValuePair的一个新实例替换整个条目来纠正。

PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。