zoukankan      html  css  js  c++  java
  • C#6新特性,让你的代码更干净

    1、集合初始化器

    //老语法,一个类想要初始化几个私有属性,那就得在构造函数上下功夫。
    public class Post { public DateTime DateCreated { get; private set; } public List<Comment> Comments { get; private set; } public Post() { DateCreated = DateTime.Now; Comments = new List<Comment>(); } } public class Comment { }

    //用新特性,我们可以这样初始化私有属性,而不用再创建构造函数

      public class Post
      {
         public DateTime DateCreated { get; private set; } = DateTime.Now;
         public List<Comment> Comments { get; private set; } = new List<Comment>();
      }

    
    

      public class Comment
      {

      }

    2、字典初始化器

        这个我倒是没发现有多么精简

     var dictionary = new Dictionary<string, string>
      {
           { "key1","value1"},
            { "key2","value2"}
       };
    
    //新特性
     var dictionary1 = new Dictionary<string, string>
      {
             ["key1"]="value1",
             ["key2"]="value2"
      };

    3、string.Format

         经常拼接字符串的对这个方法肯定不模式了,要么是string.Format,要么就是StringBuilder了。这也是我最新喜欢的一个新特性了。

    Post post = new Post();
    post.Title = "Title";
    post.Content = "Content";
    
    //通常情况下我们都这么写
    string t1= string.Format("{0}_{1}", post.Title, post.Content);
    
    
    //C#6里我们可以这么写,后台引入了$,而且支持智能提示。 
    string  t2 = $"{post.Title}_{post.Content}";
             

    4、空判断

        空判断我们也经常,C#6新特性也让新特性的代码更见简便

    //老的语法,简单却繁琐。我就觉得很繁琐
    Post post = null;
    string title = "";
    if (post != null)
    {
          title = post.Title;
    }
    
    
    //C#6新特性一句代码搞定空判断
    title = post?.Title;

     空集合判断,这种场景我们在工作当中实在见的太多,从数据库中取出来的集合,空判断、空集合判断都会遇到。

    Post post = null;
    List<Post> posts = null;
    
     if (posts != null)
     {
          post = posts[0];
      }
    
    //新特性,我们也是一句代码搞定。是不是很爽?
    post = posts?[0];

    5、getter-only 初始化器

         这个我倒没觉得是新特性,官方给出的解释是当我们要创建一个只读自动属性时我们会这样定义如下

    public class Post
    {
          public int Votes{get;private set;}
    }
    
    
    //新特性用这种方式
    public class Post
    {
         public int Votes{get;}
    }

    6、方法体表达式化

         英语是Expression Bodied Members。其实我觉的也就是Lambda的延伸,也算不上新特性。

    public class Post
     {
            
           public int AddOld()
            {
                return 1 + 1;
            }
     
           //新特性还是用Lambda的语法而已
            public int AddNew() => 1+1;
    
        }

    7、用static using来引用静态类的方法

         我完全没搞明白这个特性设计意图在哪里,本来静态方法直接调用一眼就能看出来哪个类的那个方法,现在让你用using static XXX引入类。然后直接调用其方法, 那代码不是自己写的,一眼还看不出这个方法隶属那个类。

  • 相关阅读:
    hdu 5366 简单递推
    hdu 5365 判断正方形
    hdu 3635 并查集
    hdu 4497 数论
    hdu5419 Victor and Toys
    hdu5426 Rikka with Game
    poj2074 Line of Sight
    hdu5425 Rikka with Tree II
    hdu5424 Rikka with Graph II
    poj1009 Edge Detection
  • 原文地址:https://www.cnblogs.com/tuyile006/p/6999602.html
Copyright © 2011-2022 走看看