如何在 C# 中创建 2 元组或对元组?
csharpserver side programmingprogramming更新于 2025/5/27 21:22:17
Tuple<T1, T2> 类表示 2 元组,称为对。元组是一种具有元素序列的数据结构。
示例
现在让我们看一个在 C# 中实现 2 元组的示例 −
using System;
public class Demo {
public static void Main(string[] args) {
Tuple<string,string> tuple = new Tuple<string,string>("jack", "steve");
Console.WriteLine("Value = " + tuple.Item1);
if (tuple.Item1 == "jack") {
Console.WriteLine("Exists: Tuple Value = " +tuple.Item1);
}
if (tuple.Item2 == "david") {
Console.WriteLine("Exists: Tuple Value = " +tuple.Item2);
}
}
}
输出
这将产生以下输出 −
Value = jack Exists: Tuple Value = jack
示例
现在让我们看另一个在 C# 中实现 2 元组的示例 −
using System;
public class Demo {
public static void Main(string[] args) {
Tuple tuple = new Tuple(20, "steve");
Console.WriteLine("Value = " + tuple.Item1);
if (tuple.Item1 == 20) {
Console.WriteLine("Exists: Tuple Value = " +tuple.Item1);
}
if (tuple.Item2 == "david") {
Console.WriteLine("Exists: Tuple Value = " +tuple.Item2);
}
}
}
输出
这将产生以下输出 −
Value = 20 Exists: Tuple Value = 20

