I am trying to implement an ID card using generics. I have an abstract class, Entity, and a derivation constraint on my map for Entity. Since my map must be able to create objects, my map also has a constructor constraint.
However, in order for the map to be useful, Entity subclasses should not be created from client code, which means that I need an internal constructor and no public constructors. However, this conflicts with the constructor restriction.
Is there something I am missing? Is there a way to refactor to get the desired result?
The following code compiles as is, but ideally, the constructors of the Entity subclass will be internal:
public abstract class Entity
{
public int Id { get; protected internal set; }
}
public sealed class Widget : Entity
{
public Widget() { }
}
public sealed class Gadget : Entity
{
public Gadget() { }
}
public class EntityMap<T> where T : Entity, new()
{
private Dictionary<int, T> _entities = new Dictionary<int, T>();
private object _getLock = new object();
public T Get(int id)
{
lock (_getLock)
{
if (!_entities.ContainsKey(id))
_entities.Add(id, new T() { Id = id });
}
return _entities[id];
}
internal EntityMap() { }
}
public static class ApplicationMap
{
public static EntityMap<Widget> Widgets = new EntityMap<Widget>();
public static EntityMap<Gadget> Gadgets = new EntityMap<Gadget>();
}