我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
当前回答
我创建了一个元组的c#实现,它一般解决2到5个值之间的问题-这里是博客文章,其中包含一个到源代码的链接。
其他回答
为了让上面的工作(我需要一对作为字典的键)。我必须补充一句:
public override Boolean Equals(Object o)
{
Pair<T, U> that = o as Pair<T, U>;
if (that == null)
return false;
else
return this.First.Equals(that.First) && this.Second.Equals(that.Second);
}
一旦我这样做了,我还添加了
public override Int32 GetHashCode()
{
return First.GetHashCode() ^ Second.GetHashCode();
}
禁用编译器警告。
元组从。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
如果是关于字典之类的,你要找System.Collections.Generic。KeyValuePair < TKey, TValue >。
PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。
c#在4.0版就有了元组。