我有几个“对象”都有相同的字段,让我们说:
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];
了解fristKey
和secondKey
,但没有关于“对象”精确类型的其他详细信息。
我应该如何声明这个“对象”(如果它是一个类,一个结构,如果它有const字段......)以“正确”的方式执行它,以及最友好的CPU方式(需要尽可能快地发出很多电话?
我愿意接受任何解决方案,允许我保持这些对象的区别(如果可能的话),并允许我将它们存储在Dictionary
中(这不能更改)。
我尝试将这些对象设置为静态,但由于static
对象无法继承或实现接口,因此我的字典MyTypes
无法使用我的常用“对象”。我也尝试过使用interfaced struct,但我不能使用默认构造函数或直接在“对象”声明中初始化它们,它不觉得它是最好的解决方案。
我已经在这个问题上挣扎了好几个小时,而且我已经没想完了。你的是什么?
答案 0 :(得分: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
}
答案 1 :(得分:0)
我有几个&#34;对象&#34;所有人都有相同的字段
这听起来像是基类或接口的候选者,该类的所有其他特殊类型都来自该基类或接口。为该基类命名,并使用基类&#39;字典定义中的名称:
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!
}