我正在为游戏编写一个组件实体系统,但遇到了一些障碍。我有一个List<Component>
派生类调用包含实体的所有组件的 ComponentList。我还有一个返回名为 GetComponent 的组件的方法。它通过字符串名称来完成此操作。
public Component GetComponent(string name)
{
foreach (var c in this)
{
if (c.Name == name)
return c;
}
throw new Exception("Component " + name + " does not exist.");
}
但是,当从 Component 派生一个类,将其插入 ComponentList,然后将其拉出时,我必须强制转换为该类型,这有点不方便。
TestComponent t1 = (TestComponent)Entity.ComponentList.GetComponent("Test1");
我知道有一些特殊的、神奇的方法可以使用 < T > 进行类型处理,但我不确定如何使用它,或者它是否适用于这种情况。有什么建议吗?
最佳答案
代码:
public T GetComponent<T>(string name) where T : Component
{
var result = this.FirstOrDefault(c => c.Name == name);
if( result == null )
throw new Exception("Component " + name + " does not exist.");
return (T) result;
}
用法:
var testComponent = componentFactory.GetComponent<TestComponent>("Test1");
支持此功能的语言功能称为泛型
,您可以在 MSDN 上阅读更多相关信息。 (还有很多很多其他地方;只需谷歌搜索“generics C#”)
关于c# - 从列表中返回特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943861/