• C#7.0新特性


    来源参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7

    【VS2017支持】

    1.out 变量(out variables)

      以前out参数需要在调用方法外部提前被声明,C#7.0允许out参数在方法参数传递中被声明。

      旧写法:

    int num;
    if (int.TryParse("123", out num))
    {
        Console.WriteLine(num);
    }
    else
    {
        Console.WriteLine("Could not parse!");
    }

      新写法:

    if (int.TryParse("123", out int num))
    {
        Console.WriteLine(num);
    }
    else
    {
        Console.WriteLine("Could not parse!");
    }

      out参数在方法中声明支持var隐式类型

    2.元组(Tuples)

      一个方法有多个返回类型值得解决方案,使用Tuples。

      旧写法:

    static void Main(string[] args)
    {
        var data = GetFullName();
        Console.WriteLine(data.Item1);
        Console.WriteLine(data.Item2);
        Console.WriteLine(data.Item3);
    }
    static Tuple<string, string, string> GetFullName()
    {
        return new Tuple<string, string, string>("a", "b", "c");
    }

      新写法:[需要通过nutget获取System.ValueTuple的引用]

    static void Main(string[] args)
    {
        var data = GetFullName1();
        Console.WriteLine(data.a);
        Console.WriteLine(data.b);
        Console.WriteLine(data.c);
    }
    static (string a, string b, string c) GetFullName1()
    {
        return ("a", "b", "c");
    }

      解构元组获取返回值(多个):

    static void Main(string[] args)
    {
        //不用var 定义解构元组
        (string a, string b, string c) = GetFullName1();
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
    static (string a, string b, string c) GetFullName1()
    {
        return ("a", "b", "c");
    }

    3.pattern matching(匹配模式)

      判断类型时直接赋值。

      旧写法:

    object obj = 1;
    if (obj is int) //is判断
    {
        int num1 = (int)obj; //
        int num2 = num1 + 10; //加10
        Console.WriteLine(num2); //输出
    }

      新写法:[使用反射时,考虑使用这种写法]

    object obj = 1;
    if (obj is int num1)//判断obj为int型,直接赋值给num1
    {
        int num2 = num1 + 10;
        Console.WriteLine(num2); //输出
    }

      switch的新玩法:

    static dynamic Add(object a)
    {
        dynamic data;
        switch (a)
        {
            case int b:
                data = b++;
                break;
            case string c:
                data = c + "aaa";
                break;
            default:
                data = null;
                break;
        }
        return data;
    }
  • 相关阅读:
    PlantUML —— 应用于 Eclipse 的简单快速的 UML 编辑软件
    PlantUML类图
    Java 基于log4j的日志工具类
    RabbitMQ Hello world(二)
    redis lua 初体验
    mysql 批处理 innodb_flush_at_trx_commit 测试分析
    mysql 服务日志 5.7.29
    redis 浅谈事务
    redis list 基本操作
    redis hash 基本操作
  • 原文地址:https://www.cnblogs.com/Med1tator/p/7266353.html
Copyright © 2020-2023  润新知