字典trygetvalue null

时间:2012-07-10 21:09:04

标签: c# dictionary nullreferenceexception

 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。 事件Dictionary仅用于这两个函数, 我不知道为什么值为null ...我没有在任何地方插入空值!

我在这里疯了......

3 个答案:

答案 0 :(得分:4)

可能的罪魁祸首是这一行:

b = new Bag<T>() as Bag<Event>;

as强制转换可能会失败,会将null分配给b

我的猜测是你使用Event的子类作为T的类型,并且因为Bag<T>在类型参数上不是协变的(我假设它是一个类,所以它不能,)演员表失败,你最终bnull

更新:根据以下评论,问题确实是as演员。要解决问题,只需创建new Bag<Event>(),无需强制转换。

答案 1 :(得分:0)

在某处,null与密钥类型相关联。

逐步调试调试器中的代码,并在抛出NullReferenceException之前检查字典的状态。

答案 2 :(得分:0)

NullReferenceException无法投放到Bag<T>

时会抛出

Bag<Event>

如果您将签名更改为internal void AddEvent<T>(Event ev) where T : class,则异常将被解除

相关问题