首页 > 解决方案 > 访问具有多个泛型类型的类中的静态变量

问题描述

我有一个Entity抽象的泛型类,其主要特点是它可以与同一个类的不同实现的其他实例一起分组,围绕一个共同的“组 id”。

例如,一个MoveBehaviourandFlyBehaviour可以实现Entity,因此这些类的两个给定实例可以分配给一个给定Person实例,并且可以轻松FlyBehaviour查找其对应的实例。MoveBehaviour

有人可以说我正在扼杀 OOP,所以我应该回家再也不碰电脑了,但我们改天再讨论一下吧。

这是我的尝试:

public abstract class Entity<T> where T : Entity<T>
{
    private int groupId;
    protected static Dictionary<int, T> entityMap = new Dictionary<int, T>();

    public Entity(int groupId)
    {
        this.groupId = groupId;
        entityMap.Add(groupId, (T) this);
    }

    public T2 GetCoEntity<T2>() where T2 : Entity<T2>
    {
        return T2.entityMap[groupId];
    }
}

编译器抱怨它不知道是什么entityMap,我不明白为什么。

标签: c#generics

解决方案


您需要将类类型添加到调用中:

return Entity<T2>.entityMap[groupId];

编辑

为什么需要这个?

静态方法/属性不是虚拟的,因此该entityMap对象不存在,T2因为它派生自Entity<T2>. 使用静态属性时需要使用基类型


推荐阅读