【问题标题】:Dictionary as the class property and argument to a method字典作为类属性和方法的参数
【发布时间】: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


【解决方案1】:

我建议一些不同的实现:

  1. 使用不可变实现;我怀疑我们是否要在创建实例后更改Id;可能PersonProperties 也是如此。
  2. 不要将set 公开以供收集:我们为什么要允许set,比如null 到属性?
  3. 我们可能想要很好,让 key 不区分大小写
  4. 我们应该验证构造函数的输入
  5. 让我们从业务逻辑(构造函数)中提取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);
      }
    }

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2012-01-27
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2012-03-13
    相关资源
    最近更新 更多