我有几个“对象”都具有相同的字段,比方说:
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
,但没有关于“object”精确类型的其他细节。
我应该如何声明这个“对象”(它应该是一个类,一个结构,它是否应该有常量字段......)以“正确”的方式和最 CPU 友好的方式(许多电话需要尽快发出)?
我对任何允许我保持这些对象不同(如果可能)并允许我将它们存储在 Dictionary
中的解决方案持开放态度(这无法更改)。
我尝试让这些对象成为静态对象,但由于 static
对象无法继承或实现接口(interface),因此我无法为我的字典 MyTypes
使用我的通用“对象”。我也尝试过接口(interface)结构,但我不能使用默认构造函数或直接在“对象”声明中初始化它们,感觉这不是最好的解决方案。
我已经为这个问题苦苦挣扎了好几个小时,我已经筋疲力尽了。你的是什么?
最佳答案
将接口(interface)想象成类必须遵守的契约,它可以做其他事情但必须实现接口(interface)的成员
你可以这样定义一个接口(interface)
public interface IReadOnlyNiceInterface
{
string Reference {get;}
int Id {get;}
Dictionary<string, string> Members {get;}
}
所以你的接口(interface)是只读的,实现和实例化是完全独立的
你的字典会像
Dictionary<string, IReadOnlyNiceInterface> MyTypes;
你的类型会像
public class Type1Imple : IReadOnlyNiceInterface
{
//implements member
}
关于c# - 在 C# 的字典中存储相似对象的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050672/