我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.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();
    }

禁用编译器警告。

其他回答

ui包含Pair类,因为它在ASP中被大量使用。NET 1.1作为内部ViewState结构。

2017年8月更新:c# 7.0 / . net Framework 4.7提供了一种语法,可以使用System声明具有命名项的元组。ValueTuple结构。

//explicit Item typing
(string Message, int SomeNumber) t = ("Hello", 4);
//or using implicit typing 
var t = (Message:"Hello", SomeNumber:4);

Console.WriteLine("{0} {1}", t.Message, t.SomeNumber);

更多语法示例请参见MSDN。

2012年6月更新:元组从4.0版开始就成为。net的一部分。

以下是之前的一篇文章,描述了包含in.NET4.0和对泛型的支持:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

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

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

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

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

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

元组从。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