C# 6.0中引入的新特性,以下是测试过的
1.自动的属性初始化器 Auto Property Initializer
/// <summary>
/// C#6.0 自动属性不需要编写构造器就能添加初始值
/// </summary>
public class AutoPropertyInCsharp6
{
public int PostID { get; } = 1;
public string PostName { get; } = "Post1";
public string PostTitle { get; protected set; } = string.Empty;
public AutoPropertyInCsharp6()
{
//实验证明,在构造器中PostID已经有了初始值
Console.WriteLine(PostID);
}
}
1.1 为访问器添加访问限制
public string FirstName { get; private set; }
public string LastName { get; private set; }
2.
字典初始化器 Dictionary Initializer
/// <summary>
/// 字典类型数据初始化
/// </summary>
public class DictionaryInitializerInCSharp6
{
/// <summary>
/// 之前的字典初始化器
/// </summary>
public Dictionary<string, string> List1 = new Dictionary<string, string>() {
{ "name1","12"},
{ "name2","13"},
};
/// <summary>
/// C#6.0 增加的字典初始化器
/// </summary>
public Dictionary<string, string> List2 = new Dictionary<string, string>()
{
["name1"] = "12",
["name2"] = "13",
};
}
//C#6.0 引用静态类的方式
using static System.Console;
namespace Grammar2._1
{
public class StaticUsingInCSharp6
{
public void Test1()
{
WriteLine("Static Using in C# 6");
}
}
}
4.catch 块中的 await
/// <summary>
/// 声明一个异步的方法
/// </summary>
public async void CatchTest()
{
try
{
int a = Convert.ToInt32("a");
Console.WriteLine(a);
}
catch (Exception ex)
{
await doSomething(ex);
}
}
private Task doSomething(Exception ex)
{
return Task.Run(() =>
{
Console.WriteLine("doSomething:" + ex.Message);
});
}
5.异常过滤器 Exception Filter
/// <summary>
/// try/catch 语句when关键词过滤
/// </summary>
public void CacheTest2()
{
try
{
int a = Convert.ToInt32("a");
Console.WriteLine(a);
}
catch (Exception ex) when (ex.InnerException == null)
{
Console.WriteLine("ex.InnerException为空");
}
}
6.用于检查NULL值的条件访问操作符
/// <summary>
/// 用于检查null值得条件访问操作符 ?.
/// </summary>
public void NullTest1()
{
StaticUsingInCSharp6 auto1 = new StaticUsingInCSharp6();
// StaticUsingInCSharp6 auto1 = null;
string str = null;
str = auto1?.Str ?? "空字符串";
Console.WriteLine(str);
}
public string Str { get; set; } = "abc";
7.字符串插值处理
/// <summary>
/// C# 6.0 字符串插值处理
/// </summary>
public class StringInterpolation
{
public static string Test1()
{
string first = "san";
string send = "zhang";
string result = $"{send}--{first}";
Console.WriteLine(result);
return result;
}
public static string FirstName { get; set; } = "san";
public static string SendName { get; set; } = "zhang";
public static string FullName => $"{FirstName}--{SendName}";
public static string GetAll() => $"Name:{FullName},Name2:{StringInterpolation.Test1()}";
}
MSDN说明文档:https://docs.microsoft.com/zh-cn/dotnet/articles/csharp/csharp-6
参考文件:http://www.oschina.net/translate/new-features-in-csharp