簡體   English   中英

在 C# 中的字典中存儲類似對象的最佳方法是什么?

[英]What is the best way to store similar objects in a dictionary in C#?

我有幾個“對象”都具有相同的字段,讓我們說:

public string Reference;
public int Id;
public Dictionary<string, string> Members;

它們都將在啟動時初始化一次,因此它們可能是static但我必須以這種方式讀取它們的字段:

Dictionary<string, "object"> MyTypes;
//all my objects are store in this varaible (either by value or reference)

string thisMember = MyTypes[firstKey].Members[secondKey];

知道fristKeysecondKey ,但沒有關於“對象”精確類型的其他詳細信息。

我應該如何聲明這個“對象”(它應該是一個類,一個結構,它是否應該有 const 字段......)以“正確”的方式,以及最 CPU 友好的方式(需要大量調用)盡快發出)?

我對任何允許我保持這些對象不同(如果可能),並允許我將它們存儲在Dictionary解決方案持開放態度(這不能改變)。

我嘗試將這些對象設為靜態,但由於static對象無法繼承或實現接口,因此我的字典MyTypes無法擁有通用的“對象”。 我也嘗試過接口結構,但我不能使用默認構造函數或直接在“對象”聲明中初始化它們,它並不覺得它是最好的解決方案。

我已經為這個問題苦苦掙扎了幾個小時,而且我已經沒有想法了。 你的是什么?

把接口想象成一個類必須遵守的契約,它可以做其他事情但必須實現接口的成員

你可以定義一個這樣的接口

public interface IReadOnlyNiceInterface
{
    string Reference {get;}
    int Id {get;}
    Dictionary<string, string> Members {get;}
}

所以你的接口是只讀的,實現和實例化是完全獨立的

你的字典會像

Dictionary<string, IReadOnlyNiceInterface> MyTypes;

你的類型會像

public class Type1Imple : IReadOnlyNiceInterface
{
    //implements member
}

我有幾個“對象”都具有相同的字段

這聽起來像是基類或接口的候選者,該類的所有其他特殊類型都從它派生而來。 為該基類命名,並在字典定義中使用基類的名稱:

Dictionary<string, BaseClass> MyTypes;

public class BaseClass
{
    public string Reference {get; set;}
    public int Id {get; set;}
    public Dictionary<string, string> Members {get; set;}
}

public class SpecialClass : BaseClass
{
    // you can add an instance of this class to your dictionary too!
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM