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>();
如果是,為什么?
uj5u.com熱心網友回復:
我建議有點不同的實作:
- 使用不可變的實作;我懷疑我們是否要
Id在創建實體后進行更改;可能,對于PersonProperties. - 不要公開
set收集:為什么我們應該允許set,比如說,null財產? - 我們可能想要友好一點,讓 key不區分大小寫
- 我們應該驗證建構式的輸入
- 讓我們從業務邏輯(建構式)中提取UI ( )
Console.WriteLine
public class Person {
private readonly Dictionary<string, string> m_PersonProperties =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public int ID { get; }
// If we want to allow PersonProperties editing put it as
// public IDictionary<string, string> ...
public IReadOnlyDictionary<string, string> PersonProperties =>
m_PersonProperties;
public Person(int id, IEnumerable<KeyValuePair<string, string>> personInfo) {
if (null == personInfo)
throw new ArgumentNullException(nameof(personInfo));
ID = id;
foreach (var pair in personInfo)
m_PersonProperties.TryAdd(pair.Key, pair.Value);
}
public void Print() {
foreach (KeyValuePair<string, string> kvp in PersonProperties)
Console.WriteLine(kvp.Value);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/336527.html
