C#6.0新語法示例詳解
前言
一直用C#開發(fā)程序,.NET的功能越來越多,變化也挺大的,從最初的封閉,到現(xiàn)在的開源,功能不斷的增加,一直在進步。下面就來給大家詳細介紹下C#6.0新語法的相關內(nèi)容,一起來看看吧
眾所周知,c# 6.0 是在visual studio 2015中引入的。在其他的幾個版本中同樣引入一些特性,比如在c# 3.0中引入了linq,在c# 4.0中引入了動態(tài)類型dynamic,在c#5.0中引入async和await等等。
在c# 6.0更多關注了語法的改進,而不是增加新的功能。這些新的語法將有助于我們更好更方便的編寫代碼。
1、自動只讀屬性
之前屬性為如下所示,屬性賦值需在構造函數(shù)對其初始化
1 public int Id { get; set; }
2 public string Name { get; set; }
更新后
public string Name { get; set; } = "summit";
public int Age { get; set; } = 22;
public DateTime BirthDay { get; set; } = DateTime.Now.AddYears(-20);
public IList<int> AgeList
{
get;
set;
} = new List<int> { 10, 20, 30, 40, 50 };
2、直接引用靜態(tài)類
如果之前調(diào)用靜態(tài)類中的方法,如下書寫:
Math.Abs(20d);
更新后:
using static System.Math;
private void Form1_Load(object sender, EventArgs e)
{
Abs(20d);
}
3、Null 條件運算符
之前在使用對象時,需要先進性判斷是否為null
if (student!=null)
{
string fullName = student.FullName;
}
else
{
//……
}
更新后:
string fullName = student?.FullName; //如果student為空則返回Null,不為空則返回.FullNaem,注意!得到的結(jié)果一定是要支持null
4、字符串內(nèi)插
string str = $"{firstName}和{lastName}"
5、異常篩選器
try
{
}
catch(Exception e) when(e.Message.Contains("異常過濾,把符合條件的異常捕獲")
{
}
6、nameof 表達式可生成變量、類型或成員的名稱作為字符串常量
Console.WriteLine(nameof(System.Collections.Generic)); // output: Generic Console.WriteLine(nameof(List<int>)); // output: List
7、使用索引器初始化對字典進行賦值
Dictionary<int, string> messages = new Dictionary<int, string>
{
{ 404, "Page not Found"},
{ 302, "Page moved, but left a forwarding address."},
{ 500, "The web server can't come out to play today."}
};
同時也可以這樣通過索引的方式進行賦值
Dictionary<int, string> webErrors = new Dictionary<int, string>
{
[404] = "Page not Found",
[302] = "Page moved, but left a forwarding address.",
[500] = "The web server can't come out to play today."
};
8、在屬性/方法里面使用Lambda表達式
public string NameFormat => string.Format("姓名: {0}", "summit");
public void Print() => Console.WriteLine(Name);
總結(jié)
到此這篇關于C#6.0新語法的文章就介紹到這了,更多相關C#6.0新語法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于C#實現(xiàn)的仿windows左側(cè)伸縮菜單效果
這篇文章主要介紹了基于C#實現(xiàn)的仿windows左側(cè)伸縮菜單效果,比較實用的功能,需要的朋友可以參考下2014-08-08
C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼
這篇文章主要介紹了C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼,幫助大家更好的理解和學習c#,感興趣的朋友可以了解下2020-12-12
C# .net core HttpClientFactory用法及說明
這篇文章主要介紹了C# .net core HttpClientFactory用法及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
c# Winform同一數(shù)據(jù)源多個控件保持同步
通過對控件屬性設置數(shù)據(jù)源綁定,利用Windows數(shù)據(jù)更改通知這一特性,只要訂閱(設定綁定)的控件都能接收到數(shù)據(jù)的變化通知。 通過DataBindings方法實現(xiàn)雙向數(shù)據(jù)綁定2021-06-06

