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

用C#在字典中存储相似对象的最佳方法是什么?,c#,dictionary,architecture,C#,Dictionary,Architecture,我有几个“对象”都有相同的字段,比如: public string Reference; public int Id; public Dictionary<string, string> Members; 知道fristKey和secondKey,但没有关于“对象”精确类型的其他详细信息 我应该如何声明这个“对象”(应该是一个类、一个结构,应该有const字段…)以“正确”的方式和最CPU友好的方式(需要尽快发出大量调用) 我愿意接受任何解决方案,允许我保持这些对象的差异(如果可能

我有几个“对象”都有相同的字段,比如:

public string Reference;
public int Id;
public Dictionary<string, string> Members;
知道
fristKey
secondKey
,但没有关于“对象”精确类型的其他详细信息

我应该如何声明这个“对象”(应该是一个类、一个结构,应该有const字段…)以“正确”的方式和最CPU友好的方式(需要尽快发出大量调用)

我愿意接受任何解决方案,允许我保持这些对象的差异(如果可能的话),并允许我将它们存储在
字典
(这是无法更改的)

我尝试过让这些对象保持静态,但由于
静态
对象无法继承或实现接口,因此我无法为我的字典
MyTypes
设置公共“对象”。我也试过使用接口结构,但我不能使用默认构造函数,也不能在“对象”声明中直接初始化它们,我觉得这不是最好的解决方案

我已经为这个问题挣扎了好几个小时,我的思绪都快用完了。你的是什么

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

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

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!
}
字典类型;
公共类基类
{
公共字符串引用{get;set;}
公共int Id{get;set;}
公共字典成员{get;set;}
}
公共类特殊类:基类
{
//您也可以将该类的实例添加到字典中!
}

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

您可以这样定义一个接口

public interface IReadOnlyNiceInterface
{
    string Reference {get;}
    int Id {get;}
    Dictionary<string, string> Members {get;}
}
public interface IReadOnlyNiceInterface
{
    string Reference {get;}
    int Id {get;}
    Dictionary<string, string> Members {get;}
}
Dictionary<string, IReadOnlyNiceInterface> MyTypes;
public class Type1Imple : IReadOnlyNiceInterface
{
    //implements member
}