C#類繼承自泛型集合的例子
繼承自泛型字典的例子
這段代碼定義了一個多層嵌套的字典結(jié)構(gòu),旨在組織和存儲復(fù)雜的層級數(shù)據(jù)
using System; using System.Threading.Tasks; class Contract : Dictionary<string, Dictionary<string, Dictionary<string, string>>> { private readonly string type = "autodesk.data:exchange.contract.dynamo-1.0.0"; public Contract() { var contractContent = new Dictionary<string, Dictionary<string, string>> { { "contract", new Dictionary<string, string>() } }; Add(type, contractContent); } } class Program { static void Main() { // Create an instance of Contract var contract = new Contract(); // Access the outer dictionary using the predefined type key var typeKey = "autodesk.data:exchange.contract.dynamo-1.0.0"; // Check if the key exists and add data if (contract.TryGetValue(typeKey, out var contractContent)) { // Access the inner dictionary with the key "contract" if (contractContent.TryGetValue("contract", out var innerDictionary)) { // Add key-value pairs to the innermost dictionary innerDictionary["key1"] = "value1"; innerDictionary["key2"] = "value2"; // Retrieve and display values Console.WriteLine(innerDictionary["key1"]); // Outputs: value1 Console.WriteLine(innerDictionary["key2"]); // Outputs: value2 } } } }
value1 value2
再看一個Dynamo項目實例,這段代碼的目的是創(chuàng)建一個嵌套字典結(jié)構(gòu),用于存儲有關(guān)二進制引用組件的屬性數(shù)據(jù)。使用接口IPropertySet作為多態(tài)機制的基礎(chǔ)。通過嵌套字典結(jié)構(gòu)實現(xiàn)多層次數(shù)據(jù)的組織和訪問。提供靈活的屬性管理,適合復(fù)雜對象的屬性存儲場景
using System; using System.Threading.Tasks; class BinaryReferenceComponent : Dictionary<string, Dictionary<string, IPropertySet>> { private string objectId = "autodesk.data:binary.reference.component-1.0.0"; public string ObjectId { get { return objectId; } } public BinaryReferenceComponent(string binaryId) { var propertyDictionary = new Dictionary<string, IPropertySet>(); propertyDictionary.Add("String", new StringPropertySet(binaryId)); propertyDictionary.Add("Uint32", new IntPropertySet()); this.Add("binary_reference", propertyDictionary); } } class StringPropertySet : IPropertySet { public string Id { get; set; } public string Revision { get; set; } public StringPropertySet(string binaryId, string revision = "v0") { Id = binaryId; Revision = revision; } } class IntPropertySet : IPropertySet { public int End { get; set; } public int Start { get; set; } public IntPropertySet(int start = 0, int end = 8710) { End = end; Start = start; } } interface IPropertySet { } class Program { static void Main() { // Create an instance of BinaryReferenceComponent with a binaryId var binaryReference = new BinaryReferenceComponent("exampleBinaryId"); // Access ObjectId Console.WriteLine($"ObjectId: {binaryReference.ObjectId}"); // Access properties of the component if (binaryReference.TryGetValue("binary_reference", out var propertySet)) { if (propertySet.TryGetValue("String", out var stringProperty)) { var stringProp = stringProperty as StringPropertySet; Console.WriteLine($"StringProperty Id: {stringProp.Id}, Revision: {stringProp.Revision}"); } if (propertySet.TryGetValue("Uint32", out var intProperty)) { var intProp = intProperty as IntPropertySet; Console.WriteLine($"IntProperty Start: {intProp.Start}, End: {intProp.End}"); } } } }
ObjectId: autodesk.data:binary.reference.component-1.0.0 StringProperty Id: exampleBinaryId, Revision: v0 IntProperty Start: 0, End: 8710
繼承多種集合類型
在C#中,除了泛型字典外,你還可以繼承其他集合類型,例如:
- List:可以創(chuàng)建自定義列表類,但不常見,建議使用組合
- HashSet:用于無重復(fù)元素集合,但繼承并不常見
- Queue和Stack:分別用于隊列和棧的實現(xiàn)
- Collection和ReadOnlyCollection:更適合繼承,提供了更好的方法定制化能力
示例:繼承 Collection
代碼說明
?
CustomCollection<T>
??類:- 繼承自
Collection<T>
- 重寫了
InsertItem
方法,添加插入前后的自定義行為 - 定義了一個
ItemAdded
事件,當(dāng)新項目添加時觸發(fā)
- 繼承自
?
Main
??函數(shù):- 創(chuàng)建
CustomCollection<string>
的實例 - 訂閱
ItemAdded
事件,輸出添加的項信息 - 添加幾個項目并顯示集合中的所有項目
- 創(chuàng)建
關(guān)鍵點
- 事件處理: 使用事件機制通知項的添加
- 自定義行為: 通過重寫方法實現(xiàn)特定邏輯
- 靈活性:
CustomCollection<T>
可以用于任何類型的集合
using System; using System.Collections.ObjectModel; class CustomCollection<T> : Collection<T> { // Event triggered when an item is added public event Action<T> ItemAdded; // Custom implementation of InsertItem protected override void InsertItem(int index, T item) { // Add custom behavior before inserting Console.WriteLine($"Inserting item at index {index}: {item}"); base.InsertItem(index, item); // Trigger the event after inserting ItemAdded?.Invoke(item); } // Method to display all items public void DisplayItems() { Console.WriteLine("Current items in collection:"); foreach (var item in this) { Console.WriteLine(item); } } } class Program { static void Main() { // Create an instance of CustomCollection var collection = new CustomCollection<string>(); // Subscribe to the ItemAdded event collection.ItemAdded += item => Console.WriteLine($"Item added: {item}"); // Add items to the collection collection.Add("Item1"); collection.Add("Item2"); collection.Add("Item3"); // Display all items in the collection collection.DisplayItems(); } }
運行結(jié)果:
Inserting item at index 0: Item1
Item added: Item1
Inserting item at index 1: Item2
Item added: Item2
Inserting item at index 2: Item3
Item added: Item3
Current items in collection:
Item1
Item2
Item3
注意
在C#中,類繼承自泛型字典并不常見。以下是一些原因和建議:
原因
- 違背封裝原則:直接繼承集合類可能導(dǎo)致外部代碼直接操作集合內(nèi)部結(jié)構(gòu),違背封裝原則
- 集合行為的復(fù)雜性:集合類提供的行為可能不完全適合自定義類的需求,可能需要重寫大量方法。繼承集合類可能引入維護復(fù)雜性
組合優(yōu)于繼承:常用的設(shè)計模式是組合,即在類內(nèi)部包含一個集合,而不是繼承它
建議
- 使用組合:在類中定義一個集合字段,并通過方法或?qū)傩圆僮魉_@可以更好地控制訪問和行為
擴展方法:如果需要對集合進行特定操作,可以使用擴展方法來增強其功能,而不是繼承
將前面的一個繼承的例子改為使用組合,運行結(jié)果不變
using System; using System.Collections.Generic; interface IPropertySet { } class StringPropertySet : IPropertySet { public string Id { get; set; } public string Revision { get; set; } public StringPropertySet(string binaryId, string revision = "v0") { Id = binaryId; Revision = revision; } } class IntPropertySet : IPropertySet { public int End { get; set; } public int Start { get; set; } public IntPropertySet(int start = 0, int end = 8710) { End = end; Start = start; } } class BinaryReferenceComponent { private Dictionary<string, Dictionary<string, IPropertySet>> properties = new(); public string ObjectId { get; } = "autodesk.data:binary.reference.component-1.0.0"; public BinaryReferenceComponent(string binaryId) { var propertyDictionary = new Dictionary<string, IPropertySet> { { "String", new StringPropertySet(binaryId) }, { "Uint32", new IntPropertySet() } }; properties.Add("binary_reference", propertyDictionary); } public Dictionary<string, IPropertySet> GetProperties(string key) { properties.TryGetValue(key, out var result); return result; } } class Program { static void Main() { // Create an instance of BinaryReferenceComponent var binaryReference = new BinaryReferenceComponent("exampleBinaryId"); // Access ObjectId Console.WriteLine($"ObjectId: {binaryReference.ObjectId}"); // Retrieve properties using GetProperties method var properties = binaryReference.GetProperties("binary_reference"); if (properties != null) { if (properties.TryGetValue("String", out var stringProperty)) { var stringProp = stringProperty as StringPropertySet; Console.WriteLine($"StringProperty Id: {stringProp.Id}, Revision: {stringProp.Revision}"); } if (properties.TryGetValue("Uint32", out var intProperty)) { var intProp = intProperty as IntPropertySet; Console.WriteLine($"IntProperty Start: {intProp.Start}, End: {intProp.End}"); } } else { Console.WriteLine("No properties found for the given key."); } } }
參考
到此這篇關(guān)于C#類繼承自泛型集合的文章就介紹到這了,更多相關(guān)C#類繼承自泛型集合內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#基于自定義事件EventArgs實現(xiàn)發(fā)布訂閱模式
這篇文章介紹了C#基于自定義事件EventArgs實現(xiàn)發(fā)布訂閱模式的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05C#使用windows服務(wù)開啟應(yīng)用程序的方法
這篇文章主要介紹了C#使用windows服務(wù)開啟應(yīng)用程序的方法,實例分析了C#操作windows服務(wù)開啟應(yīng)用程序所遇到的問題及相關(guān)解決技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09C#如何將DataTable導(dǎo)出到Excel解決方案
由于公司項目中需要將系統(tǒng)內(nèi)用戶操作的所有日志進行轉(zhuǎn)存?zhèn)浞?,考慮到以后可能還需要還原,所以最后決定將日志數(shù)據(jù)備份到Excel中2012-11-11解決C# winForm自定義鼠標(biāo)樣式的兩種實現(xiàn)方法詳解
本篇文章是對在C#中winForm自定義鼠標(biāo)樣式的兩種實現(xiàn)方法進行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#中隱藏TabControl選項卡標(biāo)簽的解決方案
這篇文章主要介紹了C#中隱藏TabControl選項卡標(biāo)簽的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04