Am I abusing C # generics?

I tend to rely heavily on generics, but I worry that I'm abusing them.

For example, I have Entityone that contains a dictionary of subclasses Component, the type of the component is the key, and the component is the value. Examples may be PositionComponent, ColorComponentetc.

I have methods for detaching and receiving components defined as such:

class Entity
{
    Dictionary<Type, Component> components;

    //...

    void DetachComponent<T>() 
        where T : Component 
    {
        components.Remove(typeof(T));
    }

    T GetComponent<T>()
        where T : Component
    {
        return (T)components[typeof(T)];
    }
}

The alternative that I discussed was to simply use functions with the: parameter void DetachComponent(Type componentType), but I did not like to call each method:entity.DetachComponent(typeof(ColorComponent));

Is this the misuse of generics? I usually do this for container classes, as key-value pairs using types as keys make sense to me.

+4
1

.

DetachComponent - , (Type componentType).

GetComponent . .

  • GetComponent
  • DetachComponent,

, (.. , ).

+6

All Articles