C# 6.0 構文の新機能

  1. 静的使用 (静的使用)。静的クラスを参照した後、メソッド名を直接指定できます。
    old:
    using System;
    Console.WriteLine("Hello, World!");
    new:
    using static System.Console;
    WriteLine("Hello, World");
    
  2. 式メソッド 式メソッドを使用すると、ステートメントが 1 つだけあるメソッドをラムダ構文で作成できます。
    old:
    bool IsSquare(Vector2 v2)
    {
        return v2.x == v2.y;
    }
    new:
    bool IsSquare(Vector2 v2) => v2.x == v2.y;
    
    
  3. 式属性
    old:
    public string FullName
    get
    {
        return FirstName +"" + LastName;
    }
    new:
    public string FullName => FirstName +"" + LastName;
  4. プロパティの自動初期化
    old: 
    public int Age { get; set; } 
    new:
    public int Age { get; set; } = 34;
  5. 読み取り専用の自動プロパティ
    old:
    private readonly int _bookId;
    public BookId
    {
    get
    {
    return _bookId;
    }
    }
    new:
    public BookId {get;}
  6. nameof 演算子 フィールド、プロパティ、メソッド、および型の名前には、nameof を通じてアクセスできます。nameof を使用すると、名前の変更を簡単にリファクタリングできます
    old:
    public void Method(object o)
    {
        if (o == null) throw new ArgumentNullException("o");
    }
    new:
    public void Method(object o)
    {
        if (o == null) throw new ArgumentNullException(nameof(o));
    }
  7. Null 受け渡し演算子 (?.)
    handler?.Invoke(source, e);
  8. 文字列補間 ($)
    $"name={Name},age={Age}"
  9. 辞書初期化子
    old"
    var dict = new Dictionary<int, string>() { {3, "three"}, {7, "seven"} }
    new:
    var dict = new Dictionary<int, string>() { [3] = "three", [7] = "seven" }
  10. 例外フィルター
    try
     {
      throw new WebException("Request timed out..", WebExceptionStatus.Timeout);
     }
     catch (WebException webEx) when (webEx.Status == WebExceptionStatus.Timeout)
     {
      // Exception handling
     }
  11. Catch での Await の使用
    old:
    bool hasError = false;
    string errorMessage = null;
    try
    {
    //etc.
    } catch (MyException ex)
    {
    hasError = true;
    errorMessage = ex.Message;
    } 
    if (hasError)
    {
    await new MessageDialog().ShowAsync(errorMessage);
    }
    new:
    try
    {
    //etc.
    } catch (MyException ex)
    {
    await new MessageDialog().ShowAsync(ex.Message);
    }

おすすめ

転載: blog.csdn.net/st75033562/article/details/130955537