我感兴趣的是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

.net相关问答推荐

MSBuild:CopyToOutputDirectory不会将本机DLL复制到输出

如何将 signalR 添加到不同项目中的后台服务?

ECS服务无法从Cognito获取配置

Puppeteer LaunchAsync 在未打开浏览器的情况下挂起

通过 System.Net.Mail 的 VB SMTP 停止工作

比较 C# 中的双精度值

为 XML 编码文本数据的最佳方法

是否有任何 x 次的 for 循环的更短/更简单的版本?

在 Moq 中模拟泛型方法而不指定 T

.NET 4.0 中有内置的二叉搜索树吗?

什么是 SUT,它来自哪里?

将 C# 编译为本机?

如何在可取消的异步/等待中处理 TransactionScope?

我不了解应用程序域

react 式扩展使用的好例子

解密 .NET clr20r3 异常参数 P1..P10

形成两个列表并集的最简单方法

Guid.Parse() 或 new Guid() - 有什么区别?

使用 DateTime.ToString() 时获取日期后缀

如何隐藏 WPF ListView 的标题?