前幾天看一個朋友的博客時,看他用到了C#6的特性,而6出來這麼長時間還沒有正兒八經看過它,今兒專門看了下新特性,說白了也不過是語法糖而已。但是用起來確實能讓你的代碼更加干淨些。Let's try it.
//老語法,一個類想要初始化幾個私有屬性,那就得在構造函數上下功夫。
public class Post { public DateTime DateCreated { get; private set; } public List<Comment> Comments { get; private set; } public Post() { DateCreated = DateTime.Now; Comments = new List<Comment>(); } } public class Comment { }
//用新特性,我們可以這樣初始化私有屬性,而不用再創建構造函數
public class Post
{
public DateTime DateCreated { get; private set; } = DateTime.Now;
public List<Comment> Comments { get; private set; } = new List<Comment>();
}
public class Comment
{
}
這個我倒是沒發現有多麼精簡
var dictionary = new Dictionary<string, string>
{
{ "key1","value1"},
{ "key2","value2"}
};
//新特性
var dictionary1 = new Dictionary<string, string>
{
["key1"]="value1",
["key2"]="value2"
};
經常拼接字符串的對這個方法肯定不模式了,要麼是string.Format,要麼就是StringBuilder了。這也是我最新喜歡的一個新特性了。
Post post = new Post();
post.Title = "Title";
post.Content = "Content";
//通常情況下我們都這麼寫
string t1= string.Format("{0}_{1}", post.Title, post.Content);
//C#6裡我們可以這麼寫,後台引入了$,而且支持智能提示。
string t2 = $"{post.Title}_{post.Content}";
空判斷我們也經常,C#6新特性也讓新特性的代碼更見簡便
//老的語法,簡單卻繁瑣。我就覺得很繁瑣
Post post = null;
string title = "";
if (post != null)
{
title = post.Title;
}
//C#6新特性一句代碼搞定空判斷
title = post?.Title;
空集合判斷,這種場景我們在工作當中實在見的太多,從數據庫中取出來的集合,空判斷、空集合判斷都會遇到。
Post post = null;
List<Post> posts = null;
if (posts != null)
{
post = posts[0];
}
//新特性,我們也是一句代碼搞定。是不是很爽?
post = posts?[0];
這個我倒沒覺得是新特性,官方給出的解釋是當我們要創建一個只讀自動屬性時我們會這樣定義如下
public class Post
{
public int Votes{get;private set;}
}
//新特性用這種方式
public class Post
{
public int Votes{get;}
}
英語是Expression Bodied Members。其實我覺的也就是Lambda的延伸,也算不上新特性。
public class Post
{
public int AddOld()
{
return 1 + 1;
}
//新特性還是用Lambda的語法而已
public int AddNew() => 1+1;
}
我完全沒搞明白這個特性設計意圖在哪裡,本來靜態方法直接調用一眼就能看出來哪個類的那個方法,現在讓你用using static XXX引入類。然後直接調用其方法, 那代碼不是自己寫的,一眼還看不出這個方法隸屬那個類。
其中的string插值和空判斷是我最喜歡的特性了,當然收集的可能不全,歡迎補充。 同時我很期待微軟好好把ASP.NET Core開發下。做點對.net負責的產品。