Skip to main content
 首页 » 编程设计

c#之myCollection.Add() 与 myCollection ["key"的性能]

2024年02月24日18lovecherry

在处理键/值对的集合时,使用它的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"); 

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

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

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