前言

一直用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);

总结

到此这篇关于c#6.0新语法的文章就介绍到这了,更多相关c#6.0新语法内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!