我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是: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
其他回答
为了让上面的工作(我需要一对作为字典的键)。我必须补充一句:
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();
}
禁用编译器警告。
根据您想要实现的目标,您可能想尝试KeyValuePair。
不能更改条目的键当然可以通过简单地用KeyValuePair的一个新实例替换整个条目来纠正。
如果是关于字典之类的,你要找System.Collections.Generic。KeyValuePair < TKey, TValue >。
PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。
我通常将Tuple类扩展到我自己的泛型包装器中,如下所示:
public class Statistic<T> : Tuple<string, T>
{
public Statistic(string name, T value) : base(name, value) { }
public string Name { get { return this.Item1; } }
public T Value { get { return this.Item2; } }
}
像这样使用它:
public class StatSummary{
public Statistic<double> NetProfit { get; set; }
public Statistic<int> NumberOfTrades { get; set; }
public StatSummary(double totalNetProfit, int numberOfTrades)
{
this.TotalNetProfit = new Statistic<double>("Total Net Profit", totalNetProfit);
this.NumberOfTrades = new Statistic<int>("Number of Trades", numberOfTrades);
}
}
StatSummary summary = new StatSummary(750.50, 30);
Console.WriteLine("Name: " + summary.NetProfit.Name + " Value: " + summary.NetProfit.Value);
Console.WriteLine("Name: " + summary.NumberOfTrades.Value + " Value: " + summary.NumberOfTrades.Value);