gpt4 book ai didi

c# - 如何重命名返回的元组项目?

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:17 24 4
gpt4 key购买 nike

我是 C# 新功能 Called as Tuples 的新手。我在元组上写了一些代码。当方法返回元组时(元组包含多个值)。

我-我

string firstNumber = separateNumbers.Item1;
string secondNumber = separateNumbers.Item2;
string thirdNumber = separateNumbers.Item3;
string fourthNumber = separateNumbers.Item4;

在真实场景中,识别哪个项目包含哪个值变得很复杂?

所以我想提供一些特定的名称,而不是 item1、item2 等...怎么做 ?

提前致谢。

代码:

namespace CSharp_Tuples
{
class Program
{
static void Main(string[] args)
{
string PhoneNumbers = "+92315 +92316 +92317 +92318";
var separateNumbers = GetIndividualNumbers(PhoneNumbers);

string firstNumber = separateNumbers.Item1;
string secondNumber = separateNumbers.Item2;
string thirdNumber = separateNumbers.Item3;
string fourthNumber = separateNumbers.Item4;

Console.WriteLine(firstNumber);
Console.WriteLine(secondNumber);
Console.WriteLine(thirdNumber);
Console.WriteLine(fourthNumber);

}
static Tuple<string, string, string, string> GetIndividualNumbers(string allNumbers)
{
string[] numbers = allNumbers.Split(' ');
return Tuple.Create<string,string,string,string>(numbers[0],numbers[1],numbers[2],numbers[3]);
}
}
}

最佳答案

C# 7.0 tuples feature使用 ValueTuple ,不是旧的Tuple .

使用该功能,您可以执行以下操作:

namespace CSharp_Tuples
{
class Program
{
static void Main(string[] args)
{
string PhoneNumbers = "+92315 +92316 +92317 +92318";

var numbers = UsingValueTuple(PhoneNumbers);

Console.WriteLine("firstNumber : " + numbers.firstNumber);
Console.WriteLine("secondNumber : " + numbers.secondNumer);
Console.WriteLine("thirdNumber : " + numbers.thirdNumber);
Console.WriteLine("fourthNumber : " + numbers.fourthNumber);
}

static (string firstNumber, string secondNumer, string thirdNumber, string fourthNumber) UsingValueTuple(string allNumbers)
{
string[] numbers = allNumbers.Split(' ');
return (numbers[0], numbers[1], numbers[2], numbers[3]);
}
}
}

关于c# - 如何重命名返回的元组项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com