c# - 访问具有多个泛型类型的类中的静态变量
问题描述
我有一个Entity
抽象的泛型类,其主要特点是它可以与同一个类的不同实现的其他实例一起分组,围绕一个共同的“组 id”。
例如,一个MoveBehaviour
andFlyBehaviour
可以实现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
,我不明白为什么。
解决方案
您需要将类类型添加到调用中:
return Entity<T2>.entityMap[groupId];
编辑
为什么需要这个?
静态方法/属性不是虚拟的,因此该entityMap
对象不存在,T2
因为它派生自Entity<T2>
. 使用静态属性时需要使用基类型
推荐阅读
- java - Spring boot HATEOAS 不会自动添加相关资源的链接
- c# - 组合框的子类在代码中有效,但在设计器 vs2017 中无效
- android - 从网站中查找一些播放列表信息
- python - 使用 gensim 加载 LdaMallet 模型并对看不见的文档进行分类的正确方法
- python - 如何将抓取的项目放入 Pyqt5 小部件?
- kotlin - 如何从列表中删除字符“a”?
- javascript - 预期可迭代,但没有找到一个字段
- python - 运行执行 shell 脚本并输入密码的 Python 代码
- php - 将电子邮件收据条带化给客户
- c# - opengl 透明度无法按预期工作