Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用参数重新定义属性_C#_Properties - Fatal编程技术网

C# 使用参数重新定义属性

C# 使用参数重新定义属性,c#,properties,C#,Properties,我定义了一个类属性算法,如下所示: public InputParametersProperty InputParameters { get; set; } public class InputParametersProperty { private Dictionary<string, object> inputParameters = new Dictionary<string, object>(); public object this[strin

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

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

但是我得到了错误:
对象引用未设置为对象的实例

您从未将InputParameters属性实例化为任何对象。这就是为什么您会遇到
NullReferenceException

更改:

public InputParametersProperty InputParameters { get; set; }
致:


您从未将InputParameters属性实例化为任何对象。这就是为什么您会遇到
NullReferenceException

更改:

public InputParametersProperty InputParameters { get; set; }
致:


算法
的构造函数中,是否将
输入参数
设置为新的
输入参数属性
对象,还是将其保持为空?在
算法
的构造函数中,是否将
输入参数
设置为新的
输入参数属性
对象,还是保持为null?他可以在构造函数中执行它。@romoku,如果他从类继承而不调用
base()
或其他东西,则会导致问题。我的方法对OOP更友好。在C#中,派生类型将自动调用其基本无参数构造函数。@romoku,除非属性是
virtual
,并且在继承链中的某个位置被重写。这可能会导致问题。如果派生类型(或基类型)没有无参数构造函数怎么办?@romoku同样,如果
InputParametersProperty
实例占用12313080320 mb内存怎么办?我的方法是在第一次访问它时(如果曾经访问过的话)加载它。当包含该属性的类被实例化时,您的类将加载它。他可以在构造函数中执行该操作。@romoku如果从该类继承而不调用
base()
或其他东西,则会导致问题。我的方法对OOP更友好。在C#中,派生类型将自动调用其基本无参数构造函数。@romoku,除非属性是
virtual
,并且在继承链中的某个位置被重写。这可能会导致问题。如果派生类型(或基类型)没有无参数构造函数怎么办?@romoku同样,如果
InputParametersProperty
实例占用12313080320 mb内存怎么办?我的方法是在第一次访问它时(如果曾经访问过的话)加载它。当包含属性的类被实例化时,将加载它。
private InputParametersProperty _inputParameters;
public InputParametersProperty InputParameters
{
    get
    {
        return _inputparameters ?? (_inputparameters = new InputParametersProperty()); 
    }
}