编程语言
首页 > 编程语言> > c#元组

c#元组

作者:互联网

Tuple是C# 4.0时出的新特性,.Net Framework 4.0以上版本可用。ValueTuple是C# 7.0的新特性之一,.Net Framework 4.7以上版本可用。

一、Tuple

.Net Framework元组仅支持1到7个元组元素,如果有8个元素或者更多,需要使用Tuple的嵌套和Rest属性去实现。

1.创建元组

var testTuple6 = new Tuple<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);
Console.WriteLine($"Item 1: {testTuple6.Item1}, Item 6: {testTuple6.Item6}");

2.从方法返回多个值

 

     static Tuple<string, int, uint> GetStudentInfo(string name)
        {
            return new Tuple<string, int, uint>("Bob", 28, 175);
        }
        static void RunTest()
        {
            var studentInfo = GetStudentInfo("Bob");
            Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");
        }

 

 

二、ValueTuple

1.创建元组

 

var testTuple6 = new ValueTuple<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);

 

2.从方法返回多个值

 

static (string name, int age, uint height) GetStudentInfo1(string name)
{
    return ("Bob", 28, 175);
}
static void RunTest1()
{
    var studentInfo = GetStudentInfo1("Bob");
    Console.WriteLine($"Student Information: Name [{studentInfo.name}], Age [{studentInfo.age}], Height [{studentInfo.height}]");
}

 

3.解构ValueTuple

 

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}]");
}

 

标签:Console,name,Tuple,c#,元组,studentInfo,var,Bob
来源: https://www.cnblogs.com/yxzstruggle/p/15264952.html