当用键/值对的集合是处理存在使用它的Add()方法和直接分配给它有何区别?

例如,一个HtmlGenericControl将具有属性集合:

var anchor = new HtmlGenericControl("a");

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

纯粹是它偏好的问题,或者是有这样做的一个或另一个原因?

有帮助吗?

解决方案

它们等同为您的使用,在这种情况下,运行以下命令:

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"条目)抛出重复条目错误。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top