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。事件字典仅在这两个函数中使用,我不知道为什么值为null……我不会在任何地方插入空值!
我快疯了..。
发布于 2012-07-11 05:13:46
可能的罪魁祸首是下面这行:
b = new Bag<T>() as Bag<Event>;as强制转换可能会失败,这会将null分配给b。
我的猜测是,您正在使用Event的子类作为T的类型,并且由于Bag<T>在类型参数上不是协变的(我假设它是一个类,所以它不可能是一个类),所以转换失败,最终b为null。
更新:根据下面的评论,问题确实是as cast造成的。要解决这个问题,只需创建一个new Bag<Event>(),不需要强制转换。
发布于 2012-07-11 05:13:48
在某个地方,null正与键类型相关联。
单步执行调试器中的代码,并在引发NullReferenceException之前检查字典的状态。
发布于 2012-07-11 05:23:03
当Bag<T>不能强制转换为Bag<Event>时引发NullReferenceException
如果将签名更改为internal void AddEvent<T>(Event ev) where T : class,则异常将被忽略
https://stackoverflow.com/questions/11421980
复制相似问题