我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
当前回答
根据您想要实现的目标,您可能想尝试KeyValuePair。
不能更改条目的键当然可以通过简单地用KeyValuePair的一个新实例替换整个条目来纠正。
其他回答
PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。
为了让上面的工作(我需要一对作为字典的键)。我必须补充一句:
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开始,你有了System。元组<T1, T2>类:
// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);
除了自定义类或。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);
c#在4.0版就有了元组。