C# 6.0新加特性

2023-04-26,

1、自动属性的增强

1.1、自动属性初始化 (Initializers for auto-properties)

C#4.0下的果断实现不了的。

C#6.0中自动属性的初始化方式

只要接触过C#的肯定都会喜欢这种方式。真是简洁方便呀。

1.2、只读属性初始化Getter-only auto-properties

先来看一下我们之前使用的方式吧

    public class Customer
{
public string Name { get; } public Customer(string firstName,string lastName)
{
Name = firstName +" "+ lastName;
}
}

再来看一下C#6.0中

    public class Customer
{
public string FirstName { get; }="aehyok";
public string LastName { get; }="Kris"; }

和第一条自动属性初始化使用方式一致。

2、Expression bodied function members

2.1 用Lambda作为函数体Expression bodies on method-like members

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);  

再来举一个简单的例子:一个没有返回值的函数

public void Print() => Console.WriteLine(FirstName + " " + LastName);

2.2、Lambda表达式用作属性Expression bodies on property-like function members

        public override string ToString()
{
return FirstName + " " + LastName;
}

现在C#6中

    public class User
{
public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() => string.Format("{0}——{1}", FirstName, LastName); public string FullName => FirstName + " " + LastName;
}

3、引用静态类Using Static 

在Using中可以指定一个静态类,然后可以在随后的代码中直接使用静态的成员

4、空值判断Null-conditional operators  

直接来看代码和运行结果

通过结果可以发现返回的都为null,再也不像以前那样繁琐的判断null勒。

5、字符串嵌入值    

在字符串中嵌入值

之前一直使用的方式是

现在我们可以简单的通过如下的方式进行拼接

6、nameof表达式nameof expressions 

在方法参数检查时,你可能经常看到这样的代码(之前用的少,这次也算学到了)

        public static void AddCustomer(Customer customer)
{
if (customer == null)
{
throw new ArgumentNullException("customer");
}
}

里面有那个customer是我们手写的字符串,在给customer改名时,很容易把下面的那个字符串忘掉,C#6.0 nameof帮我们解决了这个问题,看看新写法

        public static void AddCustomer(Customer customer)
{
if (customer == null)
{
throw new ArgumentNullException(nameof(customer));
}
}

7、带索引的对象初始化器Index initializers   

直接通过索引进行对象的初始化,原来真的可以实现

通过这种方式可以发现字典中只有三个元素,所以也就只有这三个索引可以访问额,其他类型的对象和集合也是可以通过这种方式进行初始化的,在此就不进行一一列举了。

8、异常过滤器 (Exception filters)  

先来看一个移植过来的方法

            try
{
var numbers = new Dictionary<int, string> {[7] = "seven",[9] = "nine",[13] = "thirteen" };
}
catch (ArgumentNullException e)
{
if (e.ParamName == "customer")
{
Console.WriteLine("customer can not be null");
}
}

在微软的文档中还给出了另一种用法,这个异常会在日志记录失败时抛给上一层调用者

        private static bool Log(Exception e)
{
///处理一些日志
return false;
} static void Main(string[] args)
{ try
{
///
}
catch (Exception e){if (!Log(e))
{ }
} Console.ReadLine();
}

9、catch和finally 中的 await —— Await in catch and finally blocks

在C#5.0中,await关键字是不能出现在catch和finnaly块中的。而在6.0中

            try
{
res = await Resource.OpenAsync(…); // You could do this. …
}
catch (ResourceException e)
{
await Resource.LogAsync(res, e); // Now you can do this …
} finally
{
if (res != null)
await res.CloseAsync(); // … and this.
}

10、无参数的结构体构造函数—— Parameterless constructors in structs 

C# 6.0新加特性的相关教程结束。

《C# 6.0新加特性.doc》

下载本文的Word格式文档,以方便收藏与打印。