gpt4 book ai didi

c# - 什么是 C++ std::pair 的 C# 模拟?

转载 作者:IT王子 更新时间:2023-10-29 03:28:35 36 4
gpt4 key购买 nike

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

谢谢!

最佳答案

元组 are available since .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

关于c# - 什么是 C++ std::pair 的 C# 模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/166089/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com