C#6.0和Visual Studio 2015以及.Net 4.6是一起出现的,所以在VS2015中支持C#6.0的语法糖,现在我们就来看看C#6.0的新增语法糖.
1.新版的string.Format
string name = "Edwin";
string age = "19";
string shown = $"My name is {name},I am {age} years old~";
Console.WriteLine(shown);
int salary = 1999;
string salary_format = $"Salary is {salary:0.00}";
Console.WriteLine(salary_format);
新版的string.Format主要是使用了$符号放置在字符串前方,声明里面可以插入变量,然后用{变量}的方式来引入一个变量,并且可以用{变量:格式}的方式来为引入的变量指定格式.
2.字典集合的新旧初始化
Dictionary<string, int> dic_old = new Dictionary<string, int>();
dic_old.Add("Test1", 1);
dic_old.Add("Test2", 2);
dic_old.Add("Test3", 3);
Dictionary<string, int> dic_new = new Dictionary<string, int>()
{
["Test1"] = 1,
["Test2"] = 2,
["Test3"] = 3
};
原来我们使用字典集合的时候,无法使用初始化器初始化数据,只好一项一项添加,现在可以使用初始化器+[**key]=value**的方式初始化字典集合.
3.空引用判断符?和??判断符
先看两个问号能干什么用:
string strTest = null;
string strTest2 = strTest ?? "Test";//??操作符,表示如果操作符前方的值为null,那么返回??后面的值
所以strTest2的值就是"Test"
然后再来看看一个问号能干什么:
string value = null;
int number = value?.Length ?? 0;//这段代码的意思,如果value不是null,返回value的长度,否则返回0
string data = null;
string data_get = data?.Substring(0, 3);//表示如果data不是null,返回data.Substring(0,3)返回的值,否则返回null
你明白我的意思了吗?这个问号可以代替所有的为Null判断,如果不为Null,直接调用方法.
4.使用Lambda表达式来定义方法
这个没啥好说了,上代码吧,一眼就明白了:
public static bool IsNull(string value) => string.IsNullOrEmpty(value);
public static bool IsInt(string value, int test = -1) => int.TryParse(value, out test) && !value.Contains("-");
public static bool IsDecimal(string value, int test = -1) => int.TryParse(value, out test) && !value.Contains("-");
public static bool IsDouble(string value, int test = -1) => int.TryParse(value, out test) && !value.Contains("-");
虽然看起来这个语法很好用,但是其实这语法也很鸡肋,它只能写一句方法操作,所以,看情况使用就行.
5.自定义属性
这个更没啥好说的,直接贴代码:
public List<int> TestList { get; set; } = new List<int> { 1, 2, 3, 4 };
public string name { get; set; } = "Edwin";