在之前的文章提到 C# 6.0 的一些新功能,本篇文章將會繼續補充前一篇沒提到的。

Collection Initializer

以往在宣告 Dictionary 物件時,會用到下列語法來加入初始值:

Dictionary<string, string> dic = new Dictionary<string, string>
{
    {"A","V1" },
    {"B","V2" }
};

在 6.0 可以這樣做以增加可讀性:

Dictionary<string, string> dic = new Dictionary<string, string>
{
    ["A"] = "V1",
    ["B"] = "V2"
};

Nameof Expressions

該語法可以直接取得變數的名稱,像是這樣:

public class MyClass(int x, int y)
{
    public int x { get; set; } = x;
    public int y { get; set; } = y;

    public MyClass() :this(0,0)
    {
        Console.WriteLine("Property: " + nameof(x));
    }
}

這樣的好處在於收集 log 的相關資訊時,變數名稱的收集會變得比較有系統,以往這類的資訊都是直接 hard-coded,如果變數名稱改了,hard-coded 的部份通常是不會想到要改的,結果就是收集到錯誤的資訊(有些則是複製貼上的代價)。

 

Exception Handling

簡單的說,就是可以在 try-catch 區塊加上條件的判斷。

//exception handling
try
{
    throw new CustomException { ErrorCode = "001" };
}
catch (CustomException ex) if (ex.ErrorCode == "001")
{
    //do something
}
catch (CustomException ex) if (ex.ErrorCode == "002")
{
    //do something
}
catch (Exception ex)
{
    WriteLine(ex.Message);
}

這樣的做法,是好是壞見人見智,但也多了個選擇。

 

Null Checking Operator

應該有人寫過這樣的程式碼:

if (obj.objA != null)
{
    if (obj.objA.objB != null)
    {
        string str = obj.objA.objB.FieldValue;
    }
}

大多數的人應該很討厭寫這樣的程式碼,在 C# 6.0 可以簡化這樣的工作:

string str1 = obj?.objA?.objB?.FieldValue?;

以上面的程式碼來看,如果其中一個物件是 null 的話,最後是直接回傳一個空字串。

arrow
arrow
    全站熱搜

    卑微研究生 發表在 痞客邦 留言(0) 人氣()