c# 6.0 学习笔记

refer : 

http://www.cnblogs.com/yinrq/p/5600530.html

http://www.cnblogs.com/wolf-sun/p/5168217.html

http://www.cnblogs.com/wolf-sun/p/5172914.html

 

使用 vs2015 .net 4.6.1

 

1. nameof

public class Demo
{
    public string name { get; set; }
}
string value = nameof(Demo.name); //"name"

好处 : 类似 enum 的作用, 当要批量替换属性名字时, 有智能提示, 这样就不怕漏换了.

 

2.null 处理

public class Demo
{
    public string name { get; set; }
   public int age { get; set; }
public void doSomeThing() { } } Demo demo = null; //before if (demo != null) demo.doSomeThing(); //after demo?.doSomeThing(); //before string valuex = (demo != null) ? demo.name : "defaultValue"; //after string valuey = demo?.name ?? "defaultValue";
// for int
int? age = demo?.age;
int age = (demo?age).GetValueOrDefault();

是 null 的话后面就不会继续跑, 会直接返回 null 值,

如果是 int 也会变成 nullable 哦,看上面的例子. 

 

3. using static 

namespace Project
{
    public class Demo
    {
        public static void method()
        {

        }
    }
}

using static Project.Demo;

//before
Demo.method();
//after
method();

好处 : 不需要写 ClassName 

 

4. string interpolation

string value1 = "kelly";
string value2 = "penny";
//before
string value4 = string.Format("i love {0}, i have {1}", value1, value2); 
//after
string value3 = $"i love {value1}, i hate {value2}"; //i love kelly, i hate penny

好处 : 早就好这样了, string.Format 和 "+ +" 一样乱丫, 不过还是 js 的 `` 更好 

 

5. lambda in class method and properties

public class Demo
{ 
    //before
    public string getString1(string value)
    {
        return $"i love {value}";
    }
    //after
    public string getString2(string value) => $"i love {value}";

    //before
    public string fullname1 {
        get {
            return getString1("kelly");
        }
    }
    //after
    public string fullname => getString1("kelly"); //this feature only support get 
}

好处 : 好看一些吧

 

6. default value in class properties

//before
public class Demo1
{
    public Demo1()
    {
        this.name = "value";
    }
    public string name { get; set; }
}
//after
public class Demo2
{
    public string name { get; set; } = "value";
}

好处 : 美 

 

7. 字典

//before
Dictionary<string, string> data1 = new Dictionary<string, string>
{
    { "key1" , "value" },
    { "key2" , "value" }
};
//after
Dictionary<string, string> data2 = new Dictionary<string, string>
{
    ["key1"] = "value",
    ["key2"] = "value",
};

好处 : 比较贴近正常的赋值 data2["ket1"] = "value";

 

posted @ 2016-07-02 01:45  兴杰  阅读(1221)  评论(0编辑  收藏  举报