mardi 10 janvier 2023

How to design a container that holds different two types of object?

Hey … I am facing a pratical code challenge in my project.

Let's say I have a Model class has a property called Configration. The Model object has different type of configration. For example, The Model was made of by Two Pipe objects, then one Lock object and another ten Pipe objects and they have to be in sequence.

In my project, all entity classes are derived from an Entity class that only has Name and ID property.

Model.cs

class Model{

    public int ID { get; set; }

    public List<ConfigrationEntry<Entity>>  Config {get;set;}


}

class Pipe{
    public int Length { get; set; }
}

class Lock{
    public string Brand { get; set; }
}

So I create a ConfigrationEntry class that contains generic parameter.

class ConfigrationEntry<T> where T : Entity{

    public int Number { get; set; }

    public T Entity {get; set;}

    public ConfigrationEntry(string name, int num){
        Entity = new T (name);
        Number = num;
    }

}

However, if I want to add this ConfigrationEntry into Model.Config List. I won't allow me to do that.

class Main{

  var configEntry1 = new ConfigrationEntry<Pipe>("Test1", 10);
  var configEntry2 = new ConfigrationEntry<Lock>("Test2", 3);
  var configEntry3 = new ConfigrationEntry<Pipe>("Test3", 3);

  var Model = new Model();

  // I cannot add this entry. IDE says it has to be ConfigrationEntry<Entity> type even Entity is the base class.
  // model.Config.Add(configEntry1);
}

So what's the best practical solution for this scenario? Right now I am thinking two use Dictionary<string, int> and use string to find the object.

Aucun commentaire:

Enregistrer un commentaire