您的位置:首页 > 编程语言 > C#

c# tuple的用法

2018-10-27 23:18 926 查看

 

自从c#7.0发布之后,其中一个新特性是关于tuple的更新,使得tuple在编码中更受欢迎

先总结一下tuple的常规用法

一.回味Tuple

   Tuple的美式发音为  /ˈtjʊpəl; ˈtʌpəl (方便在讨论的时候准确发音,我是闹过笑话)

    Tuple是C# 4.0时出的一个新特性,因此.Net Framework 4.0以上版本可用。

    Tuple三部曲

    1.创建Tuple 

有两种方式可以创建tuple元祖对象,如下所示

static void Main(string[] args)
{
//1.使用tuple的静态方法创建tuple
{
//最多支持9个元素
var tuple = Tuple.Create<int, int, int, int>(1,2,3,4);

}
//2.使用构造函数构造tuple
{
var tuple = new Tuple<int>(1);
}

}

 

   2.使用tuple

static void Main(string[] args)
{
//1.使用tuple存入相关信息,替代model对象,标识一组信息
{
var tuple = new Tuple<int, string, string>(1, "张山", "1班");
}
//2.作为方法的返回值
{
var tuple = GetTuple();
}
}

static Tuple<int, int> GetTuple()
{
Tuple<int, int> tuple = new Tuple<int, int>(1, 2);
return tuple;
}

 3.tuple取值

static void Main(string[] args)
{
//1.使用tuple存入相关信息,替代model对象,标识一组信息
{
var tuple = new Tuple<int, string, string>(1, "张山", "1班");
int id = tuple.Item1;
string name = tuple.Item2;
}
//2.作为方法的返回值
{
var tuple = GetTuple();
var id = tuple.Item1;
}
}

static Tuple<int, int> GetTuple()
{
Tuple<int, int> tuple = new Tuple<int, int>(1, 2);
return tuple;
}

 以上就是tuple使用三部曲

下面在看下c#7.0关于tuple的新特性

 首先使用ValueTuple

1.先从nuget包中下载

2.使用新特性

static void Main(string[] args)
{
//1.新特性使用
{
var valueTuple = GetValueTuple();
int id = valueTuple.id;
string name = valueTuple.name;
string className = valueTuple.className;

//可以对返回参数进行解构,解析成更明确的表达
var (id1,name1,className1)= GetValueTuple();
int id2 = id1;

//忽略自己不必使用的值
var (id3, _, _) = GetValueTuple();

}

//2.常规tuple使用
{
var tuple = GetTuple();
int id = tuple.Item1;
string name = tuple.Item2;
string className = tuple.Item3;
}

}

static (int id, string name, string className) GetValueTuple()
{

return (1, "张三", "一班");
}

static Tuple<int, string, string> GetTuple()
{
Tuple<int, string, string> tuple = new Tuple<int, string, string>(1, "张三", "一班");
return tuple;
}

 

总结

1.ValueTuple的返回值写法更简洁,且方法返回声明更明确,

  因此方法调用方能够明确获取方法返回值定义的参数名

2.ValueTuple可对返回参数进行解构

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: