码迷,mamicode.com
首页 > Windows程序 > 详细

C#6.0新特性

时间:2020-07-04 01:50:24      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:cal   contain   contains   get   public   新特性   console   符号   erro   

  • 属性 

    1.什么是自动属性

      不需要定义字段 ,在编译时生产对应字段,相当于是微软提供的一个“语法糖”

        public int Age { get; set; } 

    2.只读自动属性

      使用访问修饰符修饰set

        public string Name { get; private set; } 

      也可以只申明get访问器

        public string Name { get;} 

    3.自动属性初始化

        public List<string> Names { get; set; } = new List<string>(); 

    4.使用表达式初始化

       public string FullName => $"{FirstName} {LastName}"; 

  • using static

    用于导入单个类的静态方法  private double CalculateArea(double r) => PI * r * r; 

  •  Null条件运算符

    private void EmptyJudgment()
            {
                var result = Names.Where(x => x.Contains("12"));
    
                var list = result?.ToList();
    
                var list2 = list ?? new List<string>();
            }
  1. 使用 ?. 替换如果result为null后面的ToList不会生效,返回值list为空
  2. ?? 当list不为空list2=list,如果为null则将??右侧赋值给list2
  • 字符串内嵌

    public string FullName => $"{FirstName} {LastName}";

    字符串前添加$,在{}内可以使用C#代码

  • 异常

  1. 过滤器
      private void ExceptionFilter()
            {
                try
                {
                    
                }
                catch (Exception e) when(e.Message.Contains("400"))
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

    在catch后使用when关键字进行条件筛选

  2. finally块中使用await
     private async void AwaitAtException()
            {
                try
                {
                    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                finally
                {
                    await Task.Delay(1000);
                }
            }
  • Nameof

     private string NameOfExpression()
            {
                return nameof(CSharp6);
            }

   nameof表达式的计算结果为符号的名称,例子返回值为“CSharp”

  • 使用索引器为集合初始化

     public Dictionary<int, string> Dictionary { get; set; } = new Dictionary<int, string>
            {
                [400] = "Page Not Found",
                [500] = "Server Error"
            };        

C#6.0新特性

标签:cal   contain   contains   get   public   新特性   console   符号   erro   

原文地址:https://www.cnblogs.com/doomclouds/p/13227794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!