C# 6.0 筆記

2016年12月7日 星期三

C# 6.0使用roslyn編譯器,而roslyn是被內建在VS2015,雖然VS2013可透過Nuget安裝”Microsoft.Net.Compilers”來使用C#6.0,但是不知道會不會有未知問題,所以還是建議使用VS2015來寫比較好。

 

1.Auto property enhancements (自動屬性初始化)

    class Student
    {
        public string Name { get; set; } = "Neil";

        public string Id { get; set; } = "A001";

        public DateTime DateCreated { get; private set; } = DateTime.Now;
    }

 

2.Expression-bodied funtion(成員使用lambda運算式)

    class Student
    {
        public string Name { get; set; } = "Neil";

        public string Id { get; set; } = "A001";

        public DateTime DateCreated { get; private set; } = DateTime.Now;

        //C# 6.0新增寫法
        public string GetStudentInfoNew => string.Format("Name:{0},Id:{1}", Name, Id);

        //一般寫法
        public string GetStudentInfoOld()
        {
            return string.Format("Name:{0},Id:{1}", Name, Id);
        }
    }

 

3.Using Static(使用Using 靜態命合類別)

using static System.String;//使用using static將string載入

namespace Csharp567
{
    public class Sample
    {
        public bool CheckIsNullNew(string val)
        {
            //不用string就可以直接使用IsNullOrEmpty方法
            return IsNullOrEmpty(val);
        }

        public bool CheckIsNullOld(string val)
        {
            return string.IsNullOrEmpty(val);
        }
    }
}

 

4.Null conditional operators(Null條件運算子)

public void GetStudentName()
{
    List<Student> students = null;
    students = new List<Student>() { new Student() { Name = "Neil", Id = "001" } };

    //新寫法
    if (students?[0]?.Name != null)
    {
        Console.WriteLine(string.Format("Name:{0}", students[0].Name));
    }

    //舊寫法
    if (students != null && students[0] != null && students[0].Name != null)
    {
        Console.WriteLine(string.Format("Name:{0}", students[0].Name));
    }
}

 

5.String interpolation(字串插補)

public void ShowString()
{
    string name = "Neil";
    int id = 1;
    //舊寫法
    string oldStr= string.Format("Name:{0},Id:{1}", Name, Id);
    //新寫法
    string newStr = $"Name:{Name},Id:{Id}";
}

 

 

6.nameof expressions(nameof運算子)

public void ShowStudentId()
{
    int studentId = 123;
    //用vs工具改名稱會一起更改
    string str = $"MethodName:{nameof(ShowStudentId)} ,{nameof(studentId)}:{studentId} Show Success!!";
    //result => ShowStudentId , studentId:123 Show Success!!
}

 

7.Index initializers(索引初始設定)

var studentsOld = new Dictionary<int, string>
{
    {1,"Neil" },
    {2,"Jeremy" }
};

var studentNew = new Dictionary<int, string>
{
    [1] = "Neil",
    [2] = "Jeremy"
};

 

8.Exception filters(例外過濾)

try
{
    var r = 0;
    r = 0 / 0;
}
catch (Exception ex) when (ex.Message.Contains("KeyeError")) //可filter自訂義條件
{

    Console.WriteLine($"msg: {ex.Message}");
}

Read more...