我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
当前回答
PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。
其他回答
不幸的是,没有。你可以使用System.Collections.Generic。KeyValuePair<K, V>在许多情况下。
或者,你可以使用匿名类型来处理元组,至少在本地:
var x = new { First = "x", Second = 42 };
最后一种选择是创建自己的类。
除了自定义类或。net 4.0元组,自c# 7.0以来,有一个叫做ValueTuple的新特性,它是一个可以在这种情况下使用的结构体。而不是写:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
并通过t.Item1和t.Item2访问值,你可以简单地这样做:
(string message, int count) = ("Hello", 4);
甚至:
(var message, var count) = ("Hello", 4);
为了让上面的工作(我需要一对作为字典的键)。我必须补充一句:
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();
}
禁用编译器警告。
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);