c# - 字典 trygetvalue null

标签 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。 事件字典仅在这两个函数中使用, 我不知道为什么该值为空...我不会在任何地方插入空值!

我快疯了...

最佳答案

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

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

as强制转换可能失败,这将分配 nullb .

我的猜测是您正在使用 Event 的子类作为 T 的类型,并且自 Bag<T>类型参数不是协变的(我假设它是一个类,所以它不可能是协变的),转换失败,最终得到 bnull .

更新:根据下面的评论,问题确实是 as throw 。要修复问题,只需创建一个 new Bag<Event>() ,无需 Actor 。

关于c# - 字典 trygetvalue null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421980/

相关文章:

C# WPF 将 List<T> 与 Datagrid.ItemsSource 进行比较

c# - 数组作为字典键会产生很多冲突

c# - GetAdornerLayer 神秘地返回 null

c# - 在 C# 中使用数组实现通用堆栈

c# - 可以使用 int 作为 KeyedCollection 中的键吗

java - java中的映射键值对未正确获取

c# - 什么是NullReferenceException,如何解决?

c# - 在异步上下文中添加到字典时出现 NullReferenceException

c# - 扫描自定义属性的所有类和方法的最佳实践

dictionary - 具有固定大小的 Golang 并发访问映射/数组