我感兴趣的是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相关问答推荐

.NET 7.0中的UseHttpsRedirection和IIS生产部署

CustomControl 计算自己的宽度和高度 - 使用 bounds.Height=0 调用 ArrangeOverride

仅在有换行符时捕获分隔符之间的所有文本

如何在选项卡中 Select Winforms NumericUpDown 中的所有文本?

为什么 Any() 不适用于 c# null 对象

XmlNode 值与内部文本

调用委托与方法的性能

C#:获得完整的桌面大小?

覆盖方法上的 C# 可选参数

如何从 .NET 中的流中获取 MemoryStream?

ObservableCollection<> 与 List<>

dotnet 恢复警告 NU1701

在 C# 中,为什么不能将 List 对象存储在 List 变量中

我应该如何删除 DbSet 中的所有元素?

在 .NET 中,null 的哈希码是否应该始终为零

并发字典正确用法

IronPython 与 Python .NET

.NET 中的 java.lang.IllegalStateException?

枚举和匹配属性的 C# 命名约定

泛型类的静态成员是否与特定实例相关联?