C#6.0新语法

1、自动只读属性

之前属性为如下所示,属性赋值需在构造函数对其初始化

1 public int Id { get; set; }
2 public string Name { get; set; }

 更新后

public string Name { get; set; } = "summit";
public int Age { get; set; } = 22;
public DateTime BirthDay { get; set; } = DateTime.Now.AddYears(-20);
public IList<int> AgeList
{
      get;
      set;
} = new List<int> { 10, 20, 30, 40, 50 };

2、直接引用静态类

如果之前调用静态类中的方法,如下书写:

Math.Abs(20d);

更新后:

using static System.Math;

private void Form1_Load(object sender, EventArgs e)
        {
            Abs(20d);
        }

3、Null 条件运算符

之前在使用对象时,需要先进性判断是否为null

if (student!=null)
{
    string fullName = student.FullName;
}
else
{
 //……
}

更新后:

string fullName = student?.FullName; //如果student为空则返回Null,不为空则返回.FullNaem,注意!得到的结果一定是要支持null

4、字符串内插

string str = $"{firstName}和{lastName}"

5、异常筛选器

try
{
    
}
catch(Exception e) when(e.Message.Contains("异常过滤,把符合条件的异常捕获")
{
}

6、nameof 表达式可生成变量、类型或成员的名称作为字符串常量

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List

7、使用索引器初始化对字典进行赋值

Dictionary<int, string> messages = new Dictionary<int, string>
                {
                    { 404, "Page not Found"},
                    { 302, "Page moved, but left a forwarding address."},
                    { 500, "The web server can't come out to play today."}
                };

同时也可以这样通过索引的方式进行赋值

Dictionary<int, string> webErrors = new Dictionary<int, string>
                {
                    [404] = "Page not Found",
                    [302] = "Page moved, but left a forwarding address.",
                    [500] = "The web server can't come out to play today."
                };

8、在属性/方法里面使用Lambda表达式

public string NameFormat => string.Format("姓名: {0}", "summit");
public void Print() => Console.WriteLine(Name);

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

步、步、为营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值