private Dictionary<Type, Bag<Event>> events = new Dictionary<Type, Bag<Event>>();
internal Bag<T> GetEventList<T>() where T:class
{
Type type = typeof(T);
Bag<Event> b;
if (events.TryGetValue(type, out b))
{
return b as Bag<T>;
}
else {
b = new Bag<T>() as Bag<Event>;
events[type] = b;
return b as Bag<T>;
}
}
internal void AddEvent<T>(T ev) where T:class,Event
{
Type type = typeof(T);
Bag<Event> b;
if (events.TryGetValue(type, out b))
{
b.Add(ev); // <= NullReferenceException, b is null
}
else {
b = new Bag<T>() as Bag<Event>;
events.Add(type, b);
b.Add(ev);
}
}
我总是在 AddEvent 中收到 NullReferenceException。 事件字典仅在这两个函数中使用, 我不知道为什么该值为空...我不会在任何地方插入空值!
我快疯了...
最佳答案
可能的罪魁祸首是这一行:
b = new Bag<T>() as Bag<Event>;
as
强制转换可能失败,这将分配 null
至b
.
我的猜测是您正在使用 Event
的子类作为 T
的类型,并且自 Bag<T>
类型参数不是协变的(我假设它是一个类,所以它不可能是协变的),转换失败,最终得到 b
是null
.
更新:根据下面的评论,问题确实是 as
throw 。要修复问题,只需创建一个 new Bag<Event>()
,无需 Actor 。
关于c# - 字典 trygetvalue null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421980/