使用参数重新定义属性

时间:2013-03-05 20:44:25

标签: c# properties

我定义了一个类属性算法,如下所示:

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

从另一个类我想使用表单的属性:

algorithm.InputParameters["populationSize"] = 100;

但我收到错误:Object reference not set to an instance of an object

1 个答案:

答案 0 :(得分:3)

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

变化:

public InputParametersProperty InputParameters { get; set; }

为:

private InputParametersProperty _inputParameters;
public InputParametersProperty InputParameters
{
    get
    {
        return _inputparameters ?? (_inputparameters = new InputParametersProperty()); 
    }
}