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";

 

转载于:https://www.cnblogs.com/keatkeat/p/5634672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值