c# / c++ 元组的使用
tuple_size::value > c# :如何得到元组的个数?
- 详解C# Tuple VS ValueTuple(元组类 VS 值元组)
1.1 用于单参数方法的多值传递
当函数参数仅是一个Object类型时,可以使用值元组实现传递多个值。
static void WriteStudentInfo(Object student)
{
var studentInfo = (ValueTuple<string, int, uint>)student;
Console.WriteLine($“Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]”);
}
static void RunTest()
{
var t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteStudentInfo));
t.Start(new ValueTuple<string, int, uint>(“Bob”, 28, 175));
while (t.IsAlive)
{
System.Threading.Thread.Sleep(50);
}
}
1.2 解构ValueTuple
可以通过var (x, y)或者(var x, var y)来解析值元组元素构造局部变量,同时可以使用符号”_”来忽略不需要的元素。
static (string name, int age, uint height) GetStudentInfo1(string name)
{
return (“Bob”, 28, 175);
}
static void RunTest1()
{
var (name, age, height) = GetStudentInfo1(“Bob”);
Console.WriteLine($“Student Information: Name [{name}], Age [{age}], Height [{height}]”);
(var name1, var age1, var height1) = GetStudentInfo1("Bob");
Console.WriteLine($"Student Information: Name [{name1}], Age [{age1}], Height [{height1}]");
var (_, age2, _) = GetStudentInfo1("Bob");
Console.WriteLine($"Student Information: Age [{age2}]");
}