0

I define a class property algorithm as follows:

public InputParametersProperty InputParameters { get; set; }

public class InputParametersProperty
{
    private Dictionary<string, object> inputParameters = new Dictionary<string, object>();
    public object this[string name]
    {
        get { return inputParameters[name]; }
        set
        {
            if (inputParameters == null)
                inputParameters = new Dictionary<string, object>();
            else
                inputParameters.Add(name, value);
        }
    }
}

From another class I want to use the property of the form:

algorithm.InputParameters["populationSize"] = 100;

But I get the error: Object reference not set to an instance of an object

4

1 回答 1

3

您永远不会将 InputParameters 属性实例化为任何东西。这就是你开始的原因NullReferenceException

改变:

public InputParametersProperty InputParameters { get; set; }

至:

private InputParametersProperty _inputParameters;
public InputParametersProperty InputParameters
{
    get
    {
        return _inputparameters ?? (_inputparameters = new InputParametersProperty()); 
    }
}
于 2013-03-05T20:49:01.067 回答