1

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

例如,一个 HtmlGenericControl 将有一个 Attributes 集合:

var anchor = new HtmlGenericControl("a");

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

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

4

1 回答 1

4

它们等效于您的使用,在这种情况下,运行:

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

实际上在内部调用它:

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

在二传手看起来像这样AttributeCollectionthis[string key]

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

因此,要回答这个问题,在 的情况下AttributeCollection,这只是一个偏好问题。请记住,这不适用于其他集合类型,例如Dictionary<T, TValue>. 在这种情况下["class"] = "xyz"会更新或设置值,其中.Add("class", "xyz")(如果它已经有一个"class"条目)会抛出一个重复的条目错误。

于 2010-03-24T16:28:11.807 回答