首页 > 解决方案 > 从集合持有接口返回类而不是接口

问题描述

我想创建一个小型实体组件系统示例并创建了一些组件,例如

internal struct Position : IComponent
{
    public int X { get; set; }
    public int Y { get; set; }
}

internal struct MovementSpeed : IComponent
{
    public int Value { get; set; }
}

每个组件都实现了一个当前为空的接口IComponent。当系统循环遍历实体时,我想快速找到相关组件。

我考虑创建一个字典,将组件类型作为键,将当前实体的组件作为值。

我从public Dictionary<Type, IComponent> Components { get; }

我可以使用添加组件myEntity.Components.Add(typeof(Movement), new Movement() as IComponent);

但是我怎样才能返回一个组件?我创建了一个运动系统示例

internal class Movement : ISystem
{
    public void Update()
    {
        foreach (Entity entity in EntityPool.activeEntities.Values) // Loop through all entities
        {
            Dictionary<Type, IComponent> components = entity.Components;

            if (components.TryGetValue(typeof(Position), out Position positionComponent))
            {
                if (components.TryGetValue(typeof(MovementSpeed), out MovementSpeed movementSpeedComponent))
                {
                    // TEST: move (1 * movementspeed) units
                    positionComponent.X += movementSpeedComponent.Value;
                    positionComponent.Y += movementSpeedComponent.Value;
                }
            }
        }
    }
}

if (components.TryGetValue(typeof(Position), out Position positionComponent))崩溃是因为字典的值不返回所需类型本身的组件,而是返回接口。

我怎样才能让它工作?

(是的,我知道我可以使用 ECS 框架,但出于学习目的,我想自己做)

标签: c#entity-component-system

解决方案


简短的回答:你不能。如果字典是类型,Dictionary<Type, IComponent>那么它将只返回IComponent

但是,您可以为此创建一个扩展方法:

public static class DictionaryExtensions
{
    public static TComponent GetValueOrNull<TComponent>(this Dictionary<Type, IComponent> dict) where TComponent : IComponent
    {
        dict.TryGetValue(typeof(TComponent), out IComponent component);
        return component as TComponent;
    } 
}

并使用它:

internal class Movement : ISystem
{
    public void Update()
    {
        foreach (Entity entity in EntityPool.activeEntities.Values) // Loop through all entities
        {
            var posComponent = entity.Components.GetValueOrNull<Position>();

            if (posComponent != null)
            {
                // some code
            }
        }
    }
}

推荐阅读