I’m writing a component-entity system for a game and I hit a bit of a road block. I have a List<Component> derived class call ComponentList that contains all the components for an Entity. I also have a method that returns a component called GetComponent. It does this by a string name.
public Component GetComponent(string name)
{
foreach (var c in this)
{
if (c.Name == name)
return c;
}
throw new Exception("Component " + name + " does not exist.");
}
However, when deriving a class from Component, sticking it into the ComponentList, then pulling it back out, I have to cast in to that type, which is a bit inconvenient.
TestComponent t1 = (TestComponent)Entity.ComponentList.GetComponent("Test1");
I know there is some special, magic way to take a type with < T > but I’m not sure how to use it or, if it even applicable to this situation. Any suggestion?
Code:
Usage:
The language feature enabling this is called
genericsand you can read more about it on MSDN (and many, many other places; just google for “generics C#”)