尽管调试器显示c#对象,仍抛出NullReferenceException

本文关键字:NullReferenceException 对象 调试器 显示 | 更新日期: 2023-09-27 17:49:57

我定义了以下类:

public class PerceptronNetwork : NetworkBase
{
    Neuron perceptron { get; set; }
    public PerceptronTrainer trainingMethod;
    public PerceptronNetwork(Neuron aNeuron)
    {
        this.perceptron = aNeuron;
    }
    public double train(TrainingTemplate trainingTemplate, int extMaxGenerations)
    {
        // This is simple but the ideea is suposed to be that in larger networks here
        // I do a foreach over the neurons
        double error =  this.trainingMethod.trainNetwork(trainingTemplate, perceptron,
                                                         extMaxGenerations);
        return error;
    }
}

每当我试图从主函数中使用train方法时,我都会得到错误

Object reference not set to an instance of an object.

指向perceptron对象。

尽管当我悬停在函数调用trainingTemplate, perceptron和extMaxGenerations中的每个对象上时,它们似乎都指向正确的值。

我是否在某些方面声明或实例化了它们?

尽管调试器显示c#对象,仍抛出NullReferenceException

确保this.trainingMethod已经实例化。从你的代码来看,它似乎不是。

当你传递一个空参数时,NullReferenceException不会被抛出,当你试图访问一个空引用上的成员属性/方法/字段时,它会被抛出。在您的情况下,这意味着this.trainingMethodnull

如果trainNetwork有验证码来验证传入的参数不为空,那么您很可能会得到一个ArgumentNullException,其中参数的名称指示为空。

如果trainNetwork试图在传入的null值上引用实例成员,则堆栈跟踪将从该方法开始,而不是从train开始。