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可对返回参数进行解构
相关文章推荐
- C#Tuple的用法
- C#中获取当前时间:System.DateTime.Now.ToString()用法
- C#中DirectoryInfo类、目录信息类、文件夹信息类的用法
- C# WebClient类用法实例
- C#中Directory 类的用法
- C#中缓存的基本用法总结
- C# 接口(Interface) 理解与用法
- C# winform中ListView用法
- C#中??和?分别是什么意思? 在ASP.NET开发中一些单词的标准缩写 C#SESSION丢失问题的解决办法 在C#中INTERFACE与ABSTRACT CLASS的区别 SQL命令语句小技巧 JQUERY判断CHECKBOX是否选中三种方法 JS中!=、==、!==、===的用法和区别 在对象比较中,对象相等和对象一致分别指的是什么?
- C#中的线程与同步 ManualResetEvent用法
- C#_DllImport用法和路径问题
- C#2.0泛型-Dictionary,List的用法
- C#中$的用法
- c#中集合ArrayList用法
- C# Trim() 用法
- C# ToString()用法汇总
- C#正则表达式编程(二):Regex类用法
- C#中修饰符用法“virtual(虚拟函数)、override(重载函数)、static(静态函数)、abstract(抽象函数)、sealed(密封函数)”
- C#中HttpWebRequest的用法详解
- 【转】C#中dataGridView用法实例分析