C#集合之不變集合的用法
如果對象可以改變其狀態(tài),就很難在多個同時運行的任務中使用。這些集合必須同步。如果對象不能改變器狀態(tài),就很容易在多個線程中使用。
Microsoft提供了一個新的集合庫:Microsoft Immutable Collection。顧名思義,它包含不變的集合類————創(chuàng)建后不能改變的集合類。該類在System.Collection.Immutable中定義。
//使用靜態(tài)的Create方法創(chuàng)建該數(shù)組,Create方法被重載,可以傳遞任意數(shù)量的元素 ImmutableArray<string> a1 = ImmutableArray.Create<string>(); //Add 方法不會改變不變集合本身,而是返回一個新的不變集合 ImmutableArray<string> a2 = a1.Add("Williams"); //可以一次調(diào)用多個Add方法 ImmutableArray<string> a3 = a2.Add("Ferrari").Add("Mercedes").Add("Red Bull Racing"); foreach (var item in a3) { Console.WriteLine(item); }
在使用不變數(shù)組的每個階段,都沒有復制完整的集合。相反,不變類型使用了共享狀態(tài),僅在需要時復制集合。
但是,先填充集合,再將它變成不變的數(shù)組會更高效(使用ToImmutableList方法)。需要進行一些處理時,可以再變?yōu)榭勺兊募希ㄊ褂肨oBuilder方法)。使用不變集合的提供的構(gòu)建器ImmutableList<Account>.Builder。
List<Account> accounts = new List<Account>() { new Account { Name = "Scrooge McDuck", Amount = 667377678765m }, new Account { Name = "Donald Duck", Amount = -200m }, new Account { Name = "Ludwig von Drake", Amount = 20000m }}; ImmutableList<Account> immutableAccounts = accounts.ToImmutableList(); ImmutableList<Account>.Builder builder = immutableAccounts.ToBuilder(); for (int i = 0; i < builder.Count; i++) { Account a = builder[i]; if (a.Amount > 0) { builder.Remove(a); } } ImmutableList<Account> overdrawnAccounts = builder.ToImmutable(); foreach (var item in overdrawnAccounts) { Console.WriteLine("{0} {1}", item.Name, item.Amount); } public class Account { public string Name { get; set; } public decimal Amount { get; set; } }
只讀集合(http://www.dbjr.com.cn/article/244084.htm)提供了集合的只讀視圖。在不使用只讀視圖訪問集合的情況下,該集合仍可以修改。而永遠不能改變不變的集合。
到此這篇關(guān)于C#集合之不變集合的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#筆記之EF Code First 數(shù)據(jù)模型 數(shù)據(jù)遷移
EF 中 Code First 的數(shù)據(jù)遷移網(wǎng)上有很多資料,我這份并沒什么特別。Code First 創(chuàng)建視圖網(wǎng)上也有很多資料,但好像很麻煩,而且親測好像是無效的方法(可能是我太笨,沒搞成功),我摸索出了一種簡單有效的方法,這里分享給大家2021-09-09C# 操作 access 數(shù)據(jù)庫的實例代碼
這篇文章主要介紹了C# 操作 access 數(shù)據(jù)庫的實例代碼,需要的朋友可以參考下2018-03-03淺談C# StringBuilder內(nèi)存碎片對性能的影響
這篇文章主要介紹了淺談StringBuilder內(nèi)存碎片對性能的影響,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03