C#语法新特性之元组实例详解
作者:jovenlee 时间:2022-09-20 03:05:53
1.元组(Tuple)
元组(Tuple)在4.0 的时候就有了,但元组也有些缺点,如:
1)Tuple 会影响代码的可读性,因为它的属性名都是:Item1,Item2.. 。
2)Tuple 还不够轻量级,因为它是引用类型(Class),对于一个变量要使用一个类型,有点太没必要了。
源代码如下:
// 摘要:
// 提供用于创造元组对象的静态方法。若要浏览此类型的.NET Framework 源代码,请参阅 Reference Source。
public static class Tuple
{
// 返回结果:
// 一个元组,其值 (item1)。
public static Tuple<T1> Create<T1>(T1 item1);
// 返回结果:
// 一个 2 元组,其值 (item1, ,item2)。
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2);
}
提供用于创造元组对象的静态方法
备注:上述所指 Tuple 还不够轻量级,是从某种意义上来说的或者是一种假设,即假设分配操作非常的多。
C# 7 中的元组(ValueTuple)解决了上述两个缺点:
1)ValueTuple 支持语义上的字段命名,可以为每一个属性名字自定义名称.如(int first,int second) tuple=(1,2)。
2)ValueTuple 是值类型(Struct)。
注:如果vs报没有预定义类型ValueTuple<...>的错误时,需要使用nuget命令导入: Install - Package System.ValueTuple
源代码如下(ValueTuple<...>内部原理):
public struct ValueTuple<T1, T2> : IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, ITupleInternal
{
public T1 Item1;
public T2 Item2;
int ITupleInternal.Size
{
get
{
return 2;
}
}
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
总结:元组的出现在一定程度上简化了面向对象,有些不必要或者很少使用的对象可以直接使用元组来返回,而不需要再通过类型的方式去返回
以上所述是小编给大家介绍的C#语法新特性之元组实例详解网站的支持!
来源:http://www.cnblogs.com/jovenlee/archive/2017/04/11/6689400.html
标签:c#,语法新特征,元组
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java数据结构之队列(动力节点Java学院整理)
2021-09-22 04:58:19
![](https://img.aspxhome.com/file/2023/6/65746_0s.png)
java面试题——详解HashMap和Hashtable 的区别
2023-08-06 16:38:25
C# SQLite事务操作方法分析
2022-11-23 11:15:01
IntelliJ IDEA使用git初始化仓库的使用方法
2022-05-24 12:37:26
![](https://img.aspxhome.com/file/2023/4/68534_0s.png)
springboot如何重定向外部网页
2022-11-12 05:19:19
java中synchronized(同步代码块和同步方法)详解及区别
2021-09-03 08:44:05
Android添加用户组及自定义App权限的方法
2022-09-15 20:08:53
![](https://img.aspxhome.com/file/2023/8/117118_0s.jpg)
浅谈SpringCloud实现简单的微服务架构
2023-05-22 12:59:34
![](https://img.aspxhome.com/file/2023/0/75490_0s.png)
SpringCloud OpenFeign超详细讲解模板化远程通信的实现
2023-04-27 06:43:29
C#数字图像处理之图像缩放的方法
2023-02-12 11:09:29
Iconfont(矢量图标)+iconmoon(图标svg互转)配合javascript实现社交分享系统
2023-09-28 13:23:19
![](https://img.aspxhome.com/file/2023/0/64290_0s.png)
Java 数据结构链表操作实现代码
2021-08-12 17:57:58
![](https://img.aspxhome.com/file/2023/7/92647_0s.png)
Java常用的八种排序算法及代码实现+图解
2022-04-09 13:30:06
![](https://img.aspxhome.com/file/2023/2/68132_0s.png)
java操作Apache druid的实例代码
2023-12-24 02:10:58
java 单例模式和工厂模式实例详解
2023-04-07 22:10:19
Android中使用itemdecoration实现时间线效果
2021-10-08 12:15:49
![](https://img.aspxhome.com/file/2023/5/100615_0s.png)
一天时间用Java写了个飞机大战游戏,朋友直呼高手
2023-12-11 10:51:30
![](https://img.aspxhome.com/file/2023/2/81892_0s.png)
Android自定义ViewGroup之WaterfallLayout(二)
2022-10-11 01:58:02
![](https://img.aspxhome.com/file/2023/6/103886_0s.jpg)
java Springboot实现教务管理系统
2023-01-18 00:28:12
![](https://img.aspxhome.com/file/2023/6/64906_0s.png)
unity shader实现玻璃折射效果
2022-04-16 08:22:36
![](https://img.aspxhome.com/file/2023/6/77226_0s.gif)