重写Equals时,对象引用未设置为对象的实例

时间:2013-11-12 14:25:57

标签: c# override runtime-error

我试图在我的类中重写Equals并且我得到了这个我不理解的错误“对象引用未设置为对象的实例”

我的代码:

public override bool Equals(object obj)
{
    return this.Equals((Chapter)obj);
}

public bool Equals(Chapter other)
{
    return this.KeyFromChapterName == other.KeyFromChapterName &&
        this.Name == other.Name;
}

我做错了什么?

编辑1(stacktrace):

Object reference not set to an instance of an object.
   at Wurth.TarifImageOdsFormatter.Process.Items.Chapter.Equals(Chapter other) in C:\Projet\KeyAccountExporter\Wurth.KeyAccountExporter\Wurth.TarifImageOdsFormatter.Process\Items\Chapter.cs:line 32
   at Wurth.TarifImageOdsFormatter.Process.ProgramV2.Main(String[] args) in C:\Projet\KeyAccountExporter\Wurth.KeyAccountExporter\Wurth.TarifImageOdsFormatter.Process\ProgramV2.cs:line 110

第110行是if(myChapter.Equals(OtherChapter),第32行是我开始的地方:

public bool Equals(Chapter other)
{
  return this.KeyFromChapterName == other.KeyFromChapterName &&
   this.Name == other.Name;
}

1 个答案:

答案 0 :(得分:1)

“未将对象引用设置为对象的实例”表示您尝试取消引用null引用。换句话说,尝试访问null

在您引用other.KeyFromChapterNameother.Name的其他功能中。如果此处other为空,它也会抛出该异常。

编辑:

其他选项是如果其中一个属性的实现,例如KeyFromChapterName引用null的对象。

EDIT2:

澄清一下,该属性的getter可以引用一些null:

public String KeyFromChapterName
{
    get
    {
        //I don't know what types you are dealing with here, but as an example,
        //if chapterNames is a dictionary but it's null, then this would throw
        //the nullreferenceexception up to your Equals function.
        return chapterNames[name];
    }
}