문제

When dealing with a collection of key/value pairs is there any difference between using its Add() method and directly assigning it?

For example, a HtmlGenericControl will have an Attributes Collection:

var anchor = new HtmlGenericControl("a");

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

Is it purely a matter of preference, or is there a reason for doing one or the other?

도움이 되었습니까?

해결책

They are equivalent for your use, in this case, running this:

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

Actually calls this internally:

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

In AttributeCollection the this[string key] setter looks like this:

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

So to answer the question, in the case of AttributeCollection, it's just a matter of preference. Keep in mind, this isn't true for other collection types, for example Dictionary<T, TValue>. In this case ["class"] = "xyz" would update or set the value, where .Add("class", "xyz") (if it already had a "class" entry) would throw a duplicate entry error.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top