What is C# analog of C++ std::pair?

前端 未结 14 2037
情话喂你
情话喂你 2020-11-29 16:54

I\'m interested: What is C#\'s analog of std::pair in C++? I found System.Web.UI.Pair class, but I\'d prefer something template-based.

Than

14条回答
  •  长情又很酷
    2020-11-29 17:20

    I typically extend the Tuple class into my own generic wrapper as follows:

    public class Statistic : Tuple
    {
        public Statistic(string name, T value) : base(name, value) { }
        public string Name { get { return this.Item1; } }
        public T Value { get { return this.Item2; } }
    }
    

    and use it like so:

    public class StatSummary{
          public Statistic NetProfit { get; set; }
          public Statistic NumberOfTrades { get; set; }
    
          public StatSummary(double totalNetProfit, int numberOfTrades)
          {
              this.TotalNetProfit = new Statistic("Total Net Profit", totalNetProfit);
              this.NumberOfTrades = new Statistic("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);
    

提交回复
热议问题