C#12中的Collection expressions集合表達式語法糖詳解
C#12中引入了新的語法糖來創(chuàng)建常見的集合。并且可以使用..來解構(gòu)集合,將其內(nèi)聯(lián)到另一個集合中。
支持的類型
- 數(shù)組類型,例如 int[]。
- System.Span<T> 和 System.ReadOnlySpan<T>。
- 支持常見泛型集合,例如 System.Collections.Generic.List<T>。
集合表達式使用
以下展示了如何使用集合表達式
static void Main(string[] args)
{
List<string> names1 = ["one", "two"];
List<string> names2 = ["three", "four"];
List<List<string>> names3 = [["one", "two"], ["three", "four"]];
List<List<string>> names4 = [names1, names2];
}可以看出使用方法十分簡單
集合表達式解構(gòu)
在C#12中通過..即可將一個集合解構(gòu),并將其作為另一個集合的元素。
static void Main(string[] args)
{
List<string> names1 = ["one", "two"];
List<string> names2 = ["three", "four"];
List<string> name = [.. names1, .. names2];
}自定義類型支持集合表達式
類型通過編寫 Create() 方法,和對集合類型應(yīng)用System.Runtime.CompilerServices.CollectionBuilderAttribute 選擇加入集合表達式支持。以下是個例子
[CollectionBuilder(typeof(LineBufferBuilder), "Create")]
public class LineBuffer : IEnumerable<char>
{
private readonly char[] _buffer = new char[80];
public LineBuffer(ReadOnlySpan<char> buffer)
{
int number = (_buffer.Length < buffer.Length) ? _buffer.Length : buffer.Length;
for (int i = 0; i < number; i++)
{
_buffer[i] = buffer[i];
}
}
public IEnumerator<char> GetEnumerator() => _buffer.AsEnumerable<char>().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _buffer.GetEnumerator();
}
internal static class LineBufferBuilder
{
internal static LineBuffer Create(ReadOnlySpan<char> values) => new LineBuffer(values);
}
internal class Program
{
static void Main(string[] args)
{
LineBuffer line = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'];
}
}首先,需要創(chuàng)建一個包含 Create 方法的類:LineBufferBuilder。LineBufferBuilder.Create方法必須返回 LineBuffer 對象,并且必須采用 ReadOnlySpan<char> 類型的單個參數(shù)。
最后,必須將 CollectionBuilderAttribute添加到 LineBuffer 類聲明。其中,第一個參數(shù)提供生成器類的名稱, 第二個特性提供生成器方法的名稱。
這樣一個自定義的類就可以支持集合表達式了。
到此這篇關(guān)于C#12中的Collection expressions集合表達式語法糖詳解的文章就介紹到這了,更多相關(guān)C#12語法糖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#數(shù)據(jù)綁定之將datatabel的data添加listView
這篇文章主要介紹了c#將DataTabel的data添加ListView的示例,實現(xiàn)功能是通過響應(yīng)UI Textbox 的值向ListView 綁定新添加的紀錄。 ,需要的朋友可以參考下2014-04-04
C#數(shù)據(jù)表格(DataGridView)控件的應(yīng)用案例
這篇文章主要介紹了C#數(shù)據(jù)表格(DataGridView)控件的應(yīng)用案例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
c#只讀字段和常量的區(qū)別,以及靜態(tài)構(gòu)造函數(shù)的使用實例
這篇文章主要介紹了c#只讀字段和常量的區(qū)別,以及靜態(tài)構(gòu)造函數(shù)的使用實例,有需要的朋友可以參考一下2013-12-12
Unity學(xué)習(xí)之FSM有限狀態(tài)機
這篇文章主要介紹了Unity學(xué)習(xí)之FSM有限狀態(tài)機,通過詳細的代碼案例來進行解析說明,希望這篇文章對你有所幫助2021-06-06
WinForm實現(xiàn)程序一段時間不運行自動關(guān)閉的方法
這篇文章主要介紹了WinForm實現(xiàn)程序一段時間不運行自動關(guān)閉的方法,涉及WinForm計時器及進程操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09
C#過濾DataTable中空數(shù)據(jù)和重復(fù)數(shù)據(jù)的示例代碼
這篇文章主要給大家介紹了關(guān)于C#過濾DataTable中空數(shù)據(jù)和重復(fù)數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

