C#12 中一些非常实用的功能

列表和数组范围连接

C# 12 引入了使用 .. 操作符连接列表和数组范围的能力,使得合并集合变得更加简洁。

// C# 12 之前
List<int> combinedList = firstPart.Concat(new[] {4, 5, 6}).Concat(secondPart).ToList();

// C# 12
List<int> combinedList = [..firstPart, 4, 5, 6, ..secondPart];

原始字符串文字

原始字符串文字允许在字符串中包含多行和特殊字符,无需转义序列,简化了复杂字符串的处理。

// C# 12 之前
string json = "{\n  \"name\": \"John\",\n  \"age\": 30\n}";

// C# 12
string json = """{
  "name": "John",
  "age": 30
}""";

模式匹配增强

C# 12 增强了模式匹配,使其更加灵活和强大,简化了条件逻辑的编写。

// C# 12 之前
if (obj is string s && s.Length > 10)

// C# 12
if (obj is string { Length: > 10 } s)

必需成员

required 关键字确保在对象创建时初始化某些属性,提高了代码的健壮性。

// C# 12
public class Person
{
    public required string Name { get; set; }
    public required int Age { get; set; }
}

记录结构

C# 12 引入了 record struct,提供了不可变的值类型,优化了结构的不可变性管理。

// C# 12
public record struct Point(int X, int Y);

匿名类型的With表达式

C# 12 允许对匿名类型使用 with 表达式,使得创建修改后的匿名对象副本更加简单。

// C# 12
var person = new { Name = "John", Age = 30 };
var anotherPerson = person with { Age = 31 };

泛型属性模式

泛型属性模式允许在模式匹配中使用泛型,增加了模式匹配的灵活性。

// C# 12
public class Box<T>
{
    public T Content { get; set; }
}
if (box is Box<int> { Content: var number })
{
    Console.WriteLine(number);
}
posted @ 2023-11-13 22:38  初久的私房菜  阅读(9000)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/