2 回答
TA贡献1794条经验 获得超7个赞
C# 7.0 元组功能使用 ValueTuple,而不是旧的元组。
使用该功能,您可以执行如下操作:
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]);
}
}
}
TA贡献1816条经验 获得超4个赞
进一步我研究了这个问题,我得到了结论。
结论:
关于问题:
所以我想提供一些具体的名称,而不是项目1,项目2等...如何做到这一点?
元组不允许我们重命名返回值,相反,我们可以使用匿名类型。
法典:
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);
var numbers = Cast(usingAnonymouseObject(PhoneNumbers), new {
firstNumber = "",
secondNumer = "",
thirdNumber = "",
fourthNumber = ""
});
Console.WriteLine("firstNumber : " + numbers.firstNumber);
Console.WriteLine("secondNumber : " + numbers.secondNumer);
Console.WriteLine("thirdNumber : " + numbers.thirdNumber);
Console.WriteLine("fourthNumber : " + numbers.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]);
//}
static object usingAnonymouseObject(string allNumbers)
{
string[] numbers = allNumbers.Split(' ');
return new { firstNumber = numbers[0], secondNumer = numbers[1], thirdNumber = numbers[2], fourthNumber = numbers[3] };
}
static T Cast<T>(object obj, T type)
{
return (T)obj;
}
}
}
- 2 回答
- 0 关注
- 93 浏览
添加回答
举报