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

谢谢你!


当前回答

我创建了一个元组的c#实现,它一般解决2到5个值之间的问题-这里是博客文章,其中包含一个到源代码的链接。

其他回答

我通常将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);

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

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

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

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

不幸的是,没有。你可以使用System.Collections.Generic。KeyValuePair<K, V>在许多情况下。

或者,你可以使用匿名类型来处理元组,至少在本地:

var x = new { First = "x", Second = 42 };

最后一种选择是创建自己的类。

c#在4.0版就有了元组。