C# 12.0 - Collection Expressions & Spread Operator
نویسنده: وحید نصیری
تاریخ: ۱۴۰۲/۰۹/۰۵ ۱۲:۱۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
var numbers1_CS11 = new[] { 1, 2, 3 }; var numbers1_CS_11 = new int[] { 1, 2, 3 }; int[] numbers1_CS12 = [ 1, 2, 3 ];
error CS9176: There is no target type for the collection expression.
Span<string> span1_CS11 = new string[] { "AC", "AL" }; Span<string> span1_CS12 = [ "AC", "AL" ];
ReadOnlySpan<string> readOnlySpan_CS12 = [ "Africa", "Asia", "Europa"];
int[][] array2D_CS11 =
{
new int[] { 2002, 2006, 2010},
new int[] { 2014, 2018},
new int[] { 2022, 2026, 2030}
}; int[][] array2D_CS12 =
[
[2002, 2006, 2010],
[2014, 2018],
[2022, 2026, 2030]
]; List<string> list_CS11 = new List<string> { "Item 1", "Item 2" }; List<string> list_CS12 = [ "Item 1", "Item 2" ];
// Before C#12 List<User> users = new List<User>(); // or var users = new List<User>(); // or List<User> user = new(); // C#12 List<User> users = [];
int[] numbers1_CS12 = [ 1, 2, 3 ]; int[] numbers2_CS12 = [ 4, 5, 6 ];
int[] allItems = [ ..numbers1_CS12, ..numbers2_CS12 ];
int[] allItems_CS11 = numbers1_CS12.Concat(numbers2_CS12).ToArray();
int[] join = [..a, ..b, ..c, 6, 5];
int[] a =[1, 2, 3]; Span<int> b = [2, 4, 5, 4, 4]; List<int> c = [4, 6, 6, 5]; List<int> join = [..a, ..b, ..c, 6, 5];
List<(string, int)> otherScores = [("Dave", 90), ("Bob", 80)]; (string name, int score)[] scores = [("Alice", 90), ..otherScores, ("Charlie", 70)];
public int[] WithSpread()
{
int[] data = new int[10_000];
int[] results = [..data];
return results;
} public int[] WithSpread()
{
int[] numArray1 = new int[10000];
int index1 = 0;
int[] numArray2 = new int[numArray1.Length];
int[] numArray3 = numArray1;
for (int index2 = 0; index2 < numArray3.Length; ++index2)
{
int num = numArray3[index2];
numArray2[index1] = num;
++index1;
}
return numArray2;
} using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpreadBenchmark
{
[MemoryDiagnoser]
public class Tests
{
private readonly int[] _myData = new int[10_000];
[Benchmark(Baseline = true)]
public int[] WithToArray()
{
int[] results = _myData.ToArray();
return results;
}
[Benchmark]
public int[] WithCopyTo()
{
int[] results = new int[_myData.Length];
_myData.CopyTo(results, 0);
return results;
}
[Benchmark]
public int[] WithSpread()
{
int[] results = [.._myData];
return results;
}
}
} using BenchmarkDotNet.Running; using SpreadBenchmark; BenchmarkRunner.Run<Tests>();
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.10" />
</ItemGroup>
</Project>