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

2019-01-07 03:38发布

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.

Thank you!

14条回答
地球回转人心会变
2楼-- · 2019-01-07 04:10

Depending on what you want to accomplish, you might want to try out KeyValuePair.

The fact that you cannot change the key of an entry can of course be rectified by simply replacing the entire entry by a new instance of KeyValuePair.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-07 04:13

Tuples are available since .NET4.0 and support generics:

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

In previous versions you can use System.Collections.Generic.KeyValuePair<K, V> or a solution like the following:

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; }
};

And use it like this:

Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

This outputs:

test
2

Or even this chained pairs:

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);

That outputs:

test
12
true
查看更多
看我几分像从前
4楼-- · 2019-01-07 04:14

If it's about dictionaries and the like, you're looking for System.Collections.Generic.KeyValuePair<TKey, TValue>.

查看更多
狗以群分
5楼-- · 2019-01-07 04:16

I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework

查看更多
等我变得足够好
6楼-- · 2019-01-07 04:16

Since .NET 4.0 you have System.Tuple<T1, T2> class:

// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);
查看更多
ら.Afraid
7楼-- · 2019-01-07 04:17

Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

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

and access values through t.Item1 and t.Item2, you can simply do it like that:

(string message, int count) = ("Hello", 4);

or even:

(var message, var count) = ("Hello", 4);
查看更多
登录 后发表回答