2013-03-05 68 views
0

我定义一个类属性的算法如下:带参数的重新定义性能

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

在你的构造函数'algorithm',你设置'InputParameters'到一个新的'InputParametersProperty'对象呢,还是留为空? – krillgar 2013-03-05 20:47:07

回答

3

你永远不会实例化任何InputParameters属性。这就是为什么你要开始NullReferenceException

变化:

public InputParametersProperty InputParameters { get; set; } 

到:

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

他可以在构造函数中完成它。 – Romoku 2013-03-05 20:50:03

+0

@romoku如果他从类继承而不调用'base()'或其他东西,会导致问题。我的方法更适合面向对象编程。 – 2013-03-05 20:51:29

+0

在C#中,派生类型将自动调用其基本无参数构造函数。 – Romoku 2013-03-05 20:57:03