C# 6.0可能的新特性
2016-07-20 23:34
615 查看
C# 6.0可能的新特性
1、主构造函数(Primary Constructors)主构造函数给类中的变量赋值
Before
public class Point { private int x, y; public Point(int x, int y) this.x = x; this.y = y; } }
After
public class Point(int x, int y) { private int x, y; }
2、自动属性赋值(Auto Properties)
Before
class Point { public int X { get; private set; } public int Y { get; private set; } public Point() { this.X = 100; this.Y = 100; } }
After
class Point { public int X { get; private set; } = 100; public int Y { get; private set; } = 100; }
3、using静态类(Static type using statements;)
using会把引用类的所有静态方法导入到当前命名空间Before
public double A { get { return Math.Sqrt(Math.Round(5.142)); } }
After
using System.Math; ... public double A { get { return Sqrt(Round(5.142)); } }
4、Property Expressions
Before
public double Distance { get { return Math.Sqrt((X * X) + (Y * Y)); } }
After
public double Distance => Math.Sqrt((X * X) + (Y * Y));
初看起来像Lambda表达式,其实和Lambda无关系。
5. Method Expressions
Before
public Point Move(int dx, int dy) { return new Point(X + dx1, Y + dy1); }
After
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
这个和Property Expressions类似
6、Params for enumerables
Before
Do(someEnum.ToArray()); ... public void Do(params int[] values) { ... }
After
Do(someEnum); public void Do(params IEnumerable<Point> points) { ... }
以前params是只可以修饰array类型的参数,现在多了一些类型
7、Monadic null checking(null检查运算符)
Before
if (points != null) { var next = points.FirstOrDefault(); if (next != null && next.X != null) return next.X; } return -1;
After
var bestValue = points?.FirstOrDefault()?.X ?? -1;
这个少了好几行代码,赞啊
8、Constructor type parameter inference
Before
var x = MyClass.Create(1, "X"); ... public MyClass<T1, T2> Create<T1, T2>(T1 a, T2 b) { return new MyClass<T1, T2>(a, b); }
After
var x = new MyClass(1, "X");
9、 Inline declarations for out params(内联out参数定义)
Before
int x; int.TryParse("123", out x);
After
int.TryParse("123", out int x);
说实话,这个很常用。
当然,C# 6.0的全部新特性不止这么多,限于篇幅,就整理这些,若想了解更多,请参考下面的链接。
参考资料:
http://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Documentation
http://en.wikipedia.org/wiki/.NET_Framework_version_history
http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated
http://www.kunal-chowdhury.com/2012/07/evolution-of-c-10-50-what-are-new.html
http://www.cnblogs.com/TianFang/p/3647144.html
相关文章推荐
- C#桌面办公应用-工资管理系统系列十
- 精通C#:Chapter3学习笔记
- 用C# 加密字符串后、再用C++解密字符串的各自代码
- 精通C#:Chapter2学习笔记
- IComparable和IComparer接口
- DataGridView如何快速导出Excel
- C#拓展练习之模拟键盘录入
- c# 之DataTable的扩展方法
- C#拓展练习之模拟键盘录入
- C#中Main函数为什么要static
- C#编程.函数.委托
- 用于验证码图片识别的类续(C#代码)
- C#(入门级)学习记录
- c#学习书籍推荐
- String常用方法
- 文件基本操作之获取文件基本信息
- c#之操作ini文件
- 26 c#类的组合
- C# 转换符的重载 显示、隐式转换
- [C#]合并单元格(行、列)