最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#類繼承自泛型集合的例子

 更新時間:2024年08月09日 08:58:29   作者:VinciYan  
在C#中,除了泛型字典外,你還可以繼承其他集合類型,本文通過實例代碼主要介紹了C#類繼承自泛型集合,需要的朋友可以參考下

繼承自泛型字典的例子

這段代碼定義了一個多層嵌套的字典結(jié)構(gòu),旨在組織和存儲復雜的層級數(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),用于存儲有關二進制引用組件的屬性數(shù)據(jù)。使用接口IPropertySet作為多態(tài)機制的基礎。通過嵌套字典結(jié)構(gòu)實現(xiàn)多層次數(shù)據(jù)的組織和訪問。提供靈活的屬性管理,適合復雜對象的屬性存儲場景

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:用于無重復元素集合,但繼承并不常見
  • Queue和Stack:分別用于隊列和棧的實現(xiàn)
  • Collection和ReadOnlyCollection:更適合繼承,提供了更好的方法定制化能力

示例:繼承 Collection

代碼說明

  • ?CustomCollection<T>??:

    • 繼承自Collection<T>
    • 重寫了InsertItem方法,添加插入前后的自定義行為
    • 定義了一個ItemAdded事件,當新項目添加時觸發(fā)
  • ?Main??函數(shù):

    • 創(chuàng)建CustomCollection<string>的實例
    • 訂閱ItemAdded事件,輸出添加的項信息
    • 添加幾個項目并顯示集合中的所有項目

關鍵點

  • 事件處理: 使用事件機制通知項的添加
  • 自定義行為: 通過重寫方法實現(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#中,類繼承自泛型字典并不常見。以下是一些原因和建議:

原因

  • 違背封裝原則:直接繼承集合類可能導致外部代碼直接操作集合內(nèi)部結(jié)構(gòu),違背封裝原則
  • 集合行為的復雜性:集合類提供的行為可能不完全適合自定義類的需求,可能需要重寫大量方法。繼承集合類可能引入維護復雜性
    組合優(yōu)于繼承:常用的設計模式是組合,即在類內(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.");
        }
    }
}

參考

到此這篇關于C#類繼承自泛型集合的文章就介紹到這了,更多相關C#類繼承自泛型集合內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

石河子市| 昭通市| 田东县| 华池县| 罗平县| 龙门县| 德令哈市| 旬邑县| 茂名市| 大兴区| 东明县| 扎鲁特旗| 威信县| 石渠县| 平阳县| 韩城市| 兴安盟| 沁水县| 奉节县| 平武县| 礼泉县| 商城县| 惠来县| 贡嘎县| 琼结县| 宝鸡市| 蓬溪县| 普宁市| 大宁县| 孝义市| 青河县| 莒南县| 崇礼县| 仁布县| 湘潭市| 定西市| 平原县| 冷水江市| 岑溪市| 乐平市| 绥阳县|