0

我试图在我的类中覆盖 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(堆栈跟踪):

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;
}
4

1 回答 1

1

“对象引用未设置为对象的实例”意味着您正在尝试取消引用null引用。换句话说,试图访问null.

在您引用的另一个函数中other.KeyFromChapterName,并且other.Name. 如果other这里为空,它也会抛出该异常。

编辑:

另一个选项是如果属性的实现之一,例如KeyFromChapterName引用一个对象,即null.

编辑2:

澄清一下,该属性的 getter 可以引用为空的内容:

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];
    }
}
于 2013-11-12T14:29:00.817 回答