【问题标题】:NullReferenceException while adding to dictionary [duplicate]添加到字典时出现 NullReferenceException [重复]
【发布时间】:2012-05-18 09:50:47
【问题描述】:

我正在使用instrument2Orders 字典。我使用instrument 作为键和ordersOfGlass 作为值来添加它。我的所有实例或不是null 什么证明了下面的输出,但我仍然收到System.NullReferenceException 这怎么可能?

private Dictionary<Instrument, List<Order>> instrument2Orders = new Dictionary<Instrument, List<Order>>();

.........
        public void InitialRegisterOrder(Order order)
            .....
        if (instrument2Orders.ContainsKey(instrument))
        {
            ordersOfGlass = instrument2Orders[instrument];
        }
        else
        {
            ordersOfGlass = new List<Order>();
            try
            {
                instrument2Orders.Add(instrument, ordersOfGlass);
            } catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.ToString());
                Console.WriteLine(e.InnerException);
                Console.WriteLine("XYZ! instrument = " + instrument + " ordersOfGlass = " + ordersOfGlass + " instrument2Orders = " + instrument2Orders);
            }
        }

输出:

System.NullReferenceException: ‘бл«Є  ­  ®ЎкҐЄв ­Ґ гЄ §лў Ґв ­  нЄ§Ґ¬Ї«па ®ЎкҐЄв .
   ў System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   ў MBClient.Market.InitialRegisterOrder(Order order) ў C:\Oleg\projects\MBClient\MBClient\Market.cs:бва®Є  233

XYZ! instrument = ClassCode: EQNL Ticker: GAZP. ordersOfGlass = System.Collections.Generic.List`1[Commons.Order] instrument2Orders = System.Collections.Generic.Dictionary`2[Commons.Instrument,System.Collections.Generic.List`1[Commons.Order]]

乐器类:

class Instrument
{
    //public Instrument(int id, string classCode, string ticker)
    //{
    //    this.Ticker = ticker;
    //    this.ClassCode = classCode;
    //}

    public string ClassCode { get; set; }
    public string Ticker { get; set; }
    public override string ToString()
    {
        return "ClassCode: " + ClassCode + " Ticker: " + Ticker + '.';
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }
        Instrument instrument = obj as Instrument;
        if (instrument == null)
        {
            return false;
        }
        return (ClassCode.Equals(instrument.ClassCode)) && (Ticker.Equals(instrument.Ticker));
    }

    public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7) + ClassCode.GetHashCode();
        hash = (hash * 7) + Ticker.GetHashCode();
        return hash;
    }
}

【问题讨论】:

  • 上述代码的哪一行引发了异常?
  • 您的案例中是否有多个线程正在访问 Dictionary 实例
  • 你能把“‘бл«Є ®ЎкҐЄв Ґ гЄ §лў Ґв нЄ§Ґ¬Ї«па ®ЎкҐЄв”翻译成英文吗?谷歌翻译努力想出任何有用的东西。
  • @V4Vendetta 你可能是对的。我可能会从不同的线程访问字典。
  • @V4Vendetta 我修复了线程问题,现在看来一切都很好

标签: c# dictionary


【解决方案1】:

第一直觉:仪器无效。

这个变量从何而来?不是参数,是字段吗?

【讨论】:

  • 不,null 不是 Dictionary 的有效键;请参阅msdn.microsoft.com/en-us/library/k7z0zy8k.aspx - 但是,如果 Dictionary.Add() 为 null,它将抛出 ArgumentNullException,并且 OP 的异常是 NullReferenceException
  • @MatthewWatson 你说的很对,我认为可能是线程问题,也许其他线程正在修改它
【解决方案2】:

您的 Instrument 类是否会覆盖 GetHashCode()?

如果确实如此,并且如果它取消引用一个空 ref,你会得到类似的错误(尽管堆栈跟踪似乎表明正在发生一些不同的事情......)

无论如何,当你执行 dict.Add() 时,这个程序会给你一个 NullReferenceException,即使键和值都是非空的:

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            var dict = new Dictionary<Test, Test>();
            dict.Add(test, test);
        }
    }

    public class Test
    {
        public string Value
        {
            get;
            set;
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }
    }
}

【讨论】:

  • 在主题中添加了Instrument
  • 好的,你能提供一个完整的可编译示例来说明问题吗?
  • 我让instrument2Orders 访问线程安全,这解决了问题
猜你喜欢
  • 2013-01-21
  • 2015-05-07
  • 2014-02-21
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 2014-03-12
相关资源
最近更新 更多