欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#6.0新语法示例详解

时间:2021-07-10 09:33:56|栏目:.NET代码|点击:

前言

一直用C#开发程序,.NET的功能越来越多,变化也挺大的,从最初的封闭,到现在的开源,功能不断的增加,一直在进步。下面就来给大家详细介绍下C#6.0新语法的相关内容,一起来看看吧

众所周知,c# 6.0 是在visual studio 2015中引入的。在其他的几个版本中同样引入一些特性,比如在c# 3.0中引入了linq,在c# 4.0中引入了动态类型dynamic,在c#5.0中引入async和await等等。

在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);

总结

上一篇:ASP.NET自带对象JSON字符串与实体类的转换

栏    目:.NET代码

下一篇:asp.net网站底部的版权信息实现代码且可维护

本文标题:C#6.0新语法示例详解

本文地址:http://www.codeinn.net/misctech/155469.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有