DotNETWeekly-io / DotNetWeekly

DotNet weekly newsletter
MIT License
207 stars 3 forks source link

【文章推荐】使用集合表达式重构代码 #627

Closed gaufung closed 4 months ago

gaufung commented 4 months ago

https://devblogs.microsoft.com/dotnet/refactor-your-code-with-collection-expressions/

gaufung commented 4 months ago

image

C# 12 中引入集合表达式,它可以辅助我们写出更加简洁的代码。

var numbers1 = new int[3] { 1, 2, 3 };
var numbers2 = new int[] { 1, 2, 3 };
var numbers3 = new[] { 1, 2, 3 };
int[] numbers4 = { 1, 2, 3 };

注意最后一个不能使用 var 变量。

int[] emptyCollection = [];

通过这种方式,编译器可以生成最好的的空集合表达方式。

可以使用 .. 命令,将多个集合凭借起来

int[] onetwothree = [1, 2, 3];
int[] fourfivesix = [4, 5, 6];

int[] all = [.. fourfivesix, 100, .. onetwothree];

这里可以优化我们的代码,比如 ToList

static List<Query> QueryStringToList(string queryString) => [.. from queryPart in queryString.Split('&')
                                                              let keyValue = queryPart.Split('=')
                                                              where keyValue.Length is 2
                                                              select new Query(keyValue[0], keyValue[1])];

下面两种集合初始化的方法有什么区别?

List<int> someList1 = new() { 1, 2, 3 };
List<int> someList2 = [1, 2, 3];

如果我们查看编译器生成的代码,可以发现其中的不同

List<int> list = new List<int>();
 list.Add(1);
list.Add(2);
list.Add(3);
List<int> list2 = list;
List<int> list3 = new List<int>();

CollectionsMarshal.SetCount(list3, 3);
 Span<int> span = CollectionsMarshal.AsSpan(list3);
 int num = 0;
span[num] = 1;
num++;
 span[num] = 2;
num++;
span[num] = 3;
num++;
List<int> list4 = list3;

第一种方式首先创建了一个 List 对象,然后将元素依次加入其中;第二种方式是创建 List 对象,然后修改内部集合数据大小,然后在相应的位置修改元素值。当数据量大的时候,第二种方式性能更加好。