在C#中在字典中存储类似对象的最佳方法是什么?

问题描述 投票:2回答:2

我有几个“对象”都有相同的字段,让我们说:

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无法使用我的常用“对象”。我也尝试过使用interfaced struct,但我不能使用默认构造函数或直接在“object”声明中初始化它们,它不觉得它是最好的解决方案。

几个小时我一直在努力解决这个问题而且我已经没想完了。你的是什么?

c# dictionary architecture
2个回答
1
投票

想象一下接口就像一个类必须遵守的契约,它可以做其他事情,但必须实现接口的成员

你可以定义这样的界面

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

所以你的界面是只读的,实现和实例化完全独立

你的字典就像

Dictionary<string, IReadOnlyNiceInterface> MyTypes;

你的类型就像

public class Type1Imple : IReadOnlyNiceInterface
{
    //implements member
}

0
投票

我有几个“对象”都有相同的字段

这听起来像是基类或接口的候选者,该类的所有其他特殊类型都来自该基类或接口。为该基类赋予一个名称,并在字典定义中使用基类的名称:

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!
}
© www.soinside.com 2019 - 2024. All rights reserved.