Collection expressions (syntactic sugar for collection expressions) in C#12

Collection expressions (syntactic sugar for collection expressions) in C#12 C#12 introduces new syntactic sugar for creating common collections. And you can use .. to destructure a collection and inline it into another collection. Supported types Array type, such as int[]. System.Span and System.ReadOnlySpan. Supports common generic collections, such as System.Collections.Generic.List. Using set expressions The following shows how to use set expressions static void Main(string[] args) { List names1 = [“one”, “two”]; List names2 = [“three”, “four”]; List<List> names3 = [[“one”, “two”], [“three”, “four”]]; List<List> names4 = [names1, names2]; } It can be seen that the method of use is very simple Set expression deconstruction In C#12, you can use .. to deconstruct a collection and use it as an element of another collection. static void Main(string[] args) { List names1 = [“one”, “two”]; List names2 = [“three”, “four”]; List name = [.. names1, .. names2]; } Custom types support set expressions Types are supported by writing the Create() method and applying the System.Runtime.CompilerServices.CollectionBuilderAttribute to opt-in collection expressions on the collection type. The following is an example [CollectionBuilder(typeof(LineBufferBuilder), “Create”)] public class LineBuffer : IEnumerable { private readonly char[] _buffer = new char[80]; public LineBuffer(ReadOnlySpan buffer) { int number = (_buffer.Length <…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索