2016年7月20日 星期三

news in C#6.0 CS 6.0新增功能

What's new in C# 6.0
觀看筆記
沒啥大改,有一些可以讓程式碼乾淨點的小東西
auto properties, static members, String interpolation, Expression bodied methods, Index initializer, Null-conditional operators, The nameof operator, Exception filters

auto properties

public int X{get;} // init by constructor
public int X{get;} = 5;
public int X{get;set;}
public int X{get;set;} = 5;
public MyClass(int x) { X = x;}    // init auto properties

static members

using static System.Math;
Math.Sqrt(); -> Math();

String interpolation

String.Format("({0},{1})",X,Y); -> $"({X},{Y})"

Expression bodied methods

1.
string MyMethod()
{
    return "my method";
}
->
string MyMethod() => "my method";   // => is a lambda arrow

2.
public double Dist
{
    get{return Sqrt(X*X+Y*Y);}
}
->
public double Dist => Sqrt(X*X+Y*Y);

Index initializer

var result = new JObject();    // temp var
result["x"] = X;
->
var result = new JObject(){["x"]=X};  // no need of temp var

Null-conditional operators

1.
json != null &&
jason["x"] ! =  null &&
jason["x"].Type == JTokenType.Integer;
->
jason?.["x"]?. == JTokenType.Integer;
2. trigger event
var onChanged = OnChange;    // copy form global to local , for thread safe
if (onChanged != null)
{
    onChanged(this, args);
}
->
OnChanged?.Invoke(this,args);

The nameof operator

public Point Add(Point other)
{
    if(other == null)
    {
        throw new ArgumentNullException(nameof(other));    // from "other"
    }
}

Exception filters

try
{...}
catch (ConfigurationException e) when (e.IsServere)    //instead of re throwing
{
    await LogAsync(e);    // not OK in previous version
}
finally
{
    await CloseAsync();    // not OK in previous version
}


沒有留言:

張貼留言