编程语言
首页 > 编程语言> > 详解C# Tuple VS ValueTuple(元组类 VS 值元组)

详解C# Tuple VS ValueTuple(元组类 VS 值元组)

作者:互联网

c# / c++ 元组的使用
tuple_size::value > c# :如何得到元组的个数?

  1. 详解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}]");

}

标签:Information,Console,Tuple,元组,VS,var,Bob,ValueTuple
来源: https://blog.csdn.net/weixin_41827033/article/details/113779580