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

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

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

繼承自泛型字典的例子

這段代碼定義了一個(gè)多層嵌套的字典結(jié)構(gòu),旨在組織和存儲(chǔ)復(fù)雜的層級(jí)數(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

再看一個(gè)Dynamo項(xiàng)目實(shí)例,這段代碼的目的是創(chuàng)建一個(gè)嵌套字典結(jié)構(gòu),用于存儲(chǔ)有關(guān)二進(jìn)制引用組件的屬性數(shù)據(jù)。使用接口IPropertySet作為多態(tài)機(jī)制的基礎(chǔ)。通過嵌套字典結(jié)構(gòu)實(shí)現(xiàn)多層次數(shù)據(jù)的組織和訪問。提供靈活的屬性管理,適合復(fù)雜對(duì)象的屬性存儲(chǔ)場(chǎng)景

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:分別用于隊(duì)列和棧的實(shí)現(xiàn)
  • Collection和ReadOnlyCollection:更適合繼承,提供了更好的方法定制化能力

示例:繼承 Collection

代碼說明

  • ?CustomCollection<T>??:

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

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

關(guān)鍵點(diǎn)

  • 事件處理: 使用事件機(jī)制通知項(xiàng)的添加
  • 自定義行為: 通過重寫方法實(shí)現(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();
    }
}

運(yùn)行結(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ù)雜性:集合類提供的行為可能不完全適合自定義類的需求,可能需要重寫大量方法。繼承集合類可能引入維護(hù)復(fù)雜性
    組合優(yōu)于繼承:常用的設(shè)計(jì)模式是組合,即在類內(nèi)部包含一個(gè)集合,而不是繼承它

建議

  • 使用組合:在類中定義一個(gè)集合字段,并通過方法或?qū)傩圆僮魉_@可以更好地控制訪問和行為
    擴(kuò)展方法:如果需要對(duì)集合進(jìn)行特定操作,可以使用擴(kuò)展方法來增強(qiáng)其功能,而不是繼承

將前面的一個(gè)繼承的例子改為使用組合,運(yùn)行結(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#多播委托的實(shí)現(xiàn)示例

    C#多播委托的實(shí)現(xiàn)示例

    C#中的多播委托是一種特殊的委托類型,可以持有多個(gè)方法的引用,并在調(diào)用時(shí)依次執(zhí)行這些方法,本文就來介紹一下C#多播委托的實(shí)現(xiàn)示例,感興趣的可以了解一下
    2025-12-12
  • 使用異步方式調(diào)用同步方法(實(shí)例詳解)

    使用異步方式調(diào)用同步方法(實(shí)例詳解)

    .NET Framework 允許您異步調(diào)用任何方法。為此,應(yīng)定義與您要調(diào)用的方法具有相同簽名的委托;公共語言運(yùn)行時(shí)會(huì)自動(dòng)使用適當(dāng)?shù)暮灻麨樵撐卸xBeginInvoke和EndInvoke方法
    2013-10-10
  • C#?HttpClient超時(shí)重試機(jī)制詳解

    C#?HttpClient超時(shí)重試機(jī)制詳解

    超時(shí)重試的實(shí)現(xiàn)方式可以使用循環(huán)結(jié)構(gòu),在請(qǐng)求發(fā)起后等待一定時(shí)間,若超時(shí)未收到響應(yīng),則再次發(fā)起請(qǐng)求,循環(huán)次數(shù)可以根據(jù)實(shí)際情況進(jìn)行設(shè)置,一般建議不超過三次,這篇文章主要介紹了C#?HttpClient超時(shí)重試,需要的朋友可以參考下
    2023-06-06
  • 使用C#代碼拆分或分割PDF文件的代碼示例

    使用C#代碼拆分或分割PDF文件的代碼示例

    在許多C#和.NET應(yīng)用程序中,程序化拆分PDF文件是自動(dòng)化文檔管理的重要步驟,本指南詳細(xì)介紹了如何使用Spire.PDF for .NET庫,在C#中程序化拆分或分割PDF文件,并提供了實(shí)用的方法和清晰的代碼示例,需要的朋友可以參考下
    2025-11-11
  • C#中new關(guān)鍵字的三種用法

    C#中new關(guān)鍵字的三種用法

    在C#中,new關(guān)鍵字具有多種不同的用途,主要包括以下三個(gè):作為運(yùn)算符,作為修飾符,作為泛型約束,文章通過代碼示例將這三種用法介紹的非常詳細(xì),需要的朋友可以參考下
    2024-07-07
  • C#五類運(yùn)算符使用表達(dá)式樹進(jìn)行操作

    C#五類運(yùn)算符使用表達(dá)式樹進(jìn)行操作

    這篇文章介紹了C#五類運(yùn)算符使用表達(dá)式樹進(jìn)行操作,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-01-01
  • C#基本語法簡(jiǎn)介

    C#基本語法簡(jiǎn)介

    本文詳細(xì)講解了C#的基本語法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • 最新評(píng)論

    通江县| 福泉市| 司法| 潞西市| 辽宁省| 河北省| 海口市| 方城县| 耿马| 富顺县| 潼南县| 沙田区| 区。| 遵化市| 涞水县| 杭锦旗| 泾阳县| 会泽县| 营山县| 文安县| 昔阳县| 玛沁县| 周至县| 重庆市| 香港| 左权县| 汤阴县| 秦安县| 习水县| 兴文县| 静乐县| 东阿县| 沈阳市| 桐乡市| 定襄县| 莲花县| 塔城市| 兴安盟| 二连浩特市| 宣武区| 东乌珠穆沁旗|