C++ std::pair の C# アナログ版とは何ですか? 質問する

C++ std::pair の C# アナログ版とは何ですか? 質問する

C++ におけるC# の類似物は何ですかstd::pair? クラスは見つかりましたSystem.Web.UI.Pairが、テンプレートベースのものの方が好みです。

ベストアンサー1

タプル.NET4.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

おすすめ記事