代码之家  ›  专栏  ›  技术社区  ›  Armstrongest

mycollection.add()与mycollection[“key”]的性能比较

  •  1
  • Armstrongest  · 技术社区  · 15 年前

    在处理键/值对的集合时,使用其add()方法和直接赋值有什么区别吗?

    例如,htmlgenericcontrol将有一个attributes集合:

    var anchor = new HtmlGenericControl("a");
    
    // These both work:
    anchor.Attributes.Add("class", "xyz");
    anchor.Attributes["class"] = "xyz";
    

    这纯粹是一个偏好问题,还是有理由这么做?

    1 回复  |  直到 15 年前
        1
  •  4
  •   Nick Craver    15 年前

    它们相当于供您使用,在本例中,运行以下命令:

    anchor.Attributes["class"] = "xyz";
    

    实际上在内部称之为:

    anchor.Attributes.Add("class", "xyz");
    

    AttributeCollection 这个 this[string key] setter看起来像这样:

    public string this[string key]
    {
      get { }
      set { this.Add(key, value); }
    }
    

    为了回答这个问题, 在这种情况下 属性集合 ,这只是一个偏好的问题。请记住,对于其他集合类型,这是不正确的,例如 Dictionary<T, TValue> . 在这种情况下 ["class"] = "xyz" 将更新或设置值,其中 .Add("class", "xyz") (如果它已经有了 "class" 条目)将引发重复的条目错误。