zoukankan      html  css  js  c++  java
  • C#6.0语法糖剖析(二)

    1、索引初始化

    使用代码

     var numbers2 = new Dictionary<int, string> {[7] = "seven", [9] = "nine", [13] = "thirteen"};

    编译器生成的代码

     Dictionary<int, string> dictionary2 = new Dictionary<int, string>();
        dictionary2[7] = "seven";
        dictionary2[9] = "nine";
        dictionary2[13] = "thirteen";
        Dictionary<int, string> dictionary = dictionary2;

    2、异常过滤器When

    使用代码

    try
    {
        throw new ArgumentException("string error");
    }
    catch (Exception e) when(MyFilter(e))
    {
        WriteLine(e.Message);
    }
    
    private static bool MyFilter(Exception e)
    {
        return e is ArgumentException;
    }

    When语法作用是:在进入到catch之前、验证when括号里MyFilter方法返回的bool,如果返回true继续运行,false不走catch直接抛出异常。

    使用这个filter可以更好的判断一个错误是继续处理还是重新抛出去。按照以前的做法,在catch块内如需再次抛出去,需要重新throw出去,这时的错误源是捕捉后在抛的,而不是原先的,有了when语法就可以直接定位到错误源。

    3、catch和finally代码块内的await

    Await异步处理是在c#5.0提出的,但不能在catch和finally代码块内使用,这次在C#6.0更新上支持了。

    使用代码:

    async void Solve()
    {
        try
        {
            await HttpMethodAsync();
        }
        catch (ArgumentException e)
        {
            await HttpMethodAsync();
        }
        finally
        {
            await HttpMethodAsync();
        }
    }

    3、nameof表达式

    使用代码:

    string nameOfAuthor;
    WriteLine(nameof(nameOfAuthor));

    使用nameof来获取成员变量的名称,上面会输出:"nameOfAuthor"。

  • 相关阅读:
    hdu 4183(网络流)
    hdu 1565&hdu 1569(网络流--最小点权值覆盖)
    hdu 1532(最大流)
    HDU 2141 Can you find it?
    HDU 1096 A+B for Input-Output Practice (VIII)
    HDU 1095 A+B for Input-Output Practice (VII)
    HDU 1094 A+B for Input-Output Practice (VI)
    HDU 1093 A+B for Input-Output Practice (V)
    HDU 1092 A+B for Input-Output Practice (IV)
    HDU 1091 A+B for Input-Output Practice (III)
  • 原文地址:https://www.cnblogs.com/frankyou/p/4692150.html
Copyright © 2011-2022 走看看