C#6新特性,让你的代码更干净
2016-05-26 22:41
337 查看
前言
前几天看一个朋友的博客时,看他用到了C#6的特性,而6出来这么长时间还没有正儿八经看过它,今儿专门看了下新特性,说白了也不过是语法糖而已。但是用起来确实能让你的代码更加干净些。Let'stryit.1、集合初始化器
//老语法,一个类想要初始化几个私有属性,那就得在构造函数上下功夫。 publicclassPost { publicDateTimeDateCreated{get;privateset;} publicList<Comment>Comments{get;privateset;} publicPost() { DateCreated=DateTime.Now; Comments=newList<Comment>(); } } publicclassComment { } //用新特性,我们可以这样初始化私有属性,而不用再创建构造函数
publicclassPost
{
publicDateTimeDateCreated{get;privateset;}=DateTime.Now;
publicList<Comment>Comments{get;privateset;}=newList<Comment>();
}
publicclassComment
{
}
2、字典初始化器
这个我倒是没发现有多么精简vardictionary=newDictionary<string,string>
{
{"key1","value1"},
{"key2","value2"}
};
//新特性
vardictionary1=newDictionary<string,string>
{
["key1"]="value1",
["key2"]="value2"
};
3、string.Format
经常拼接字符串的对这个方法肯定不模式了,要么是string.Format,要么就是StringBuilder了。这也是我最新喜欢的一个新特性了。Postpost=newPost();
post.Title="Title";
post.Content="Content";
//通常情况下我们都这么写
stringt1=string.Format("{0}_{1}",post.Title,post.Content);
//C#6里我们可以这么写,后台引入了$,而且支持智能提示。
stringt2=$"{post.Title}_{post.Content}";
4、空判断
空判断我们也经常,C#6新特性也让新特性的代码更见简便//老的语法,简单却繁琐。我就觉得很繁琐
Postpost=null;
stringtitle="";
if(post!=null)
{
title=post.Title;
}
//C#6新特性一句代码搞定空判断
title=post?.Title;
空集合判断,这种场景我们在工作当中实在见的太多,从数据库中取出来的集合,空判断、空集合判断都会遇到。
Postpost=null;
List<Post>posts=null;
if(posts!=null)
{
post=posts[0];
}
//新特性,我们也是一句代码搞定。是不是很爽?
post=posts?[0];
5、getter-only初始化器
这个我倒没觉得是新特性,官方给出的解释是当我们要创建一个只读自动属性时我们会这样定义如下publicclassPost
{
publicintVotes{get;privateset;}
}
//新特性用这种方式
publicclassPost
{
publicintVotes{get;}
}
6、方法体表达式化
英语是ExpressionBodiedMembers。其实我觉的也就是Lambda的延伸,也算不上新特性。publicclassPost
{
publicintAddOld()
{
return1+1;
}
//新特性还是用Lambda的语法而已
publicintAddNew()=>1+1;
}
7、用staticusing来引用静态类的方法
我完全没搞明白这个特性设计意图在哪里,本来静态方法直接调用一眼就能看出来哪个类的那个方法,现在让你用usingstaticXXX引入类。然后直接调用其方法,那代码不是自己写的,一眼还看不出这个方法隶属那个类。总结
其中的string插值和空判断是我最喜欢的特性了,当然收集的可能不全,欢迎补充。同时我很期待微软好好把ASP.NETCore开发下。做点对.net负责的产品。相关文章推荐
- C# 从Resources资源中启动应用程序,应用程序简单加壳,导出Resources中的资源为文件
- Quartz.NET c# 教程 - 课程四:Triggers
- 《Head First C#》学习 ---第二章总结
- 字符串反转C#的实现
- C# 软件下载插件,软件自动更新功能实现,通过cmd命令调用应用程序,应用程序实现单例启动
- C#中的InitializeComponent()方法
- C# ThreadPool 线程同步
- C#函数式编程之递归调用
- C#函数式编程之序列
- C#函数式编程之可选值
- C#函数式编程之标准高阶函数
- 30天C#基础巩固------了解委托,string练习
- C# MVC4 QRCode二维码生成
- 一个输入指定盘符和文件名检索文件存在路径的c#程序
- C#匿名函数的坑
- C# 将时间戳 byte[] 转换成 datetime 的几个方法
- C# ThreadPool的简单用法
- C# webservices 之自定义编写发布【2】
- C# 读取Excel文件里面的内容到DataSet
- 【转】C# Linq 交集、并集、差集、去重