开发者

Performance for myCollection.Add() vs. myCollection["key"]

When dealing 开发者_Go百科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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜