简体   繁体   中英

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

I have several "objects" all having the same fields, let's say :

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

They will all be initialized once at launch so they might be static BUT I will have to read their fields this way :

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

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

knowing fristKey and secondKey , but without having other details about the "object" precise type.

How should I declare this "object" (should it be a class, a struct, should it have const fields...) to do it the "right" way, and the most CPU-friendly way (lot of calls needs to be issued as fast as possible) ?

I'm open to any solution allowing me to keep those objects distincts (if possible), and allowing me store them in a Dictionary (this can't be changed).

I tried having those objects static but as static objects can't inherit nor implement interfaces I can't have my common "object" for my dictionary MyTypes . I also tried with interfaced struct, but I can't use a default constructor or directly initialize them in the "object" declaration, it doesn't feel it's the best solution.

I have struggling with this problem for hours and I'm running out of thoughts. What are yours?

Imagine the interface like a contract that a class must respect, it can do other things but MUST implements the member of the interface

you can define an interface like this

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

so your interface is read only, implementation and instantiation is then completely independent

your dictionary will be like

Dictionary<string, IReadOnlyNiceInterface> MyTypes;

and your types will be like

public class Type1Imple : IReadOnlyNiceInterface
{
    //implements member
}

I have several "objects" all having the same fields

That sounds like a candidate for a base class or an interface, from which all other special kinds of that class derive. Give that base class a name, and use the base classes' name in your dictionary definition:

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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM