c# - 从列表中返回特定类型

标签 c# .net

我正在为游戏编写一个组件实体系统,但遇到了一些障碍。我有一个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/

相关文章:

c# - 多线程 c# 应用程序 System.OutOfMemoryException 在运行 1~5 分钟后

c# - 将文件从一个项目复制到另一个项目时出错

c# - 如何转换 ASP.NET session 以取回我的列表?

c# - 使用C#访问系统目录

c# - 如何在 C# Winforms 中向标签添加提示或工具提示?

c# - 检查字符串中的特殊字符 (/*-+_@&$#%)?

c# - Rider 编写 Roslyn 分析器

c# - 此 SqlTransaction 已完成;它不再可用,为什么?

c# - 在完全初始化结构之前访问结构的字段

javascript - 如何在数字分页中选择脚?辐射网格