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

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负责的产品。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: