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

谢谢你!


当前回答

除了自定义类或。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);

其他回答

如果是关于字典之类的,你要找System.Collections.Generic。KeyValuePair < TKey, TValue >。

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

PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。

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

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

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

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