use*_*286 8 .net c# initialization automatic-properties
我有一个属性:
public Dictionary<string, string> MyProp { get; set; }
Run Code Online (Sandbox Code Playgroud)
当我调用该属性来添加项时,我得到一个NullReferenceException.
我如何在属性本身进行空检查,如果它为null,它会给我一个新的?同时保持自动财产模式.
谢谢!
没有显式的私有变量,唯一的另一种方法是将一些代码添加到类的构造函数中:
MyProp = new Dictionary<string,string>();
Run Code Online (Sandbox Code Playgroud)
您可以在构造函数中初始化它:
public MyClass()
{
MyProp = new Dictionary<string, string>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6776 次 |
| 最近记录: |