【发布时间】:2021-10-25 19:16:41
【问题描述】:
public class Person
{
public int ID { get; set; }
public Dictionary<string, string> PersonProperties { get; set; }
public Person(int id, Dictionary<string, string>personInfo )
{
ID = id;
PersonProperties = personInfo;
foreach (KeyValuePair<string, string> kvp in PersonProperties)
{
Console.WriteLine(kvp.Value);
}
}
}
上例中,是否需要初始化类属性PersonProperties?
类似
public Dictionary<string, string> PersonProperties { get; set; } = new Dictionary<string, string>();
如果是,为什么?
【问题讨论】:
-
是的,你需要,但你是在构造函数中做的,所以一切都很好。也许您想处理它为空的情况,例如通过抛出
ArgumentNullException。 -
@TimSchmelter 你的意思是检查构造函数内部?
-
是的,如果
null:PersonProperties = personInfo ?? throw new ArgumentNullException(nameof(personInfo));就抛出。这比等待后续错误要好。
标签: c# dictionary