简体   繁体   English

control.Attributes.Add和control.Attributes []之间的区别

[英]Difference between control.Attributes.Add and control.Attributes[]

I am setting the css class in the code behind in ASP.NET 我在ASP.NET中的代码中设置了css类

I could either do: 我可以这样做:

txtBox.Attributes.Add("class", "myClass");

or 要么

txtBox.Attributes["class"] = "myClass";
  1. What are the differences? 有什么区别?
  2. Are there any situations in which one should be used over the other? 是否有任何情况下应该使用另一个?
  3. What happens in case 1 if the class is assigned in the aspx page already? 如果已经在aspx页面中分配了类,那么在案例1中会发生什么? Does it overwrite it? 它会覆盖它吗?

1) Add adds the attribute, while [] allows you to access the value directly and assign it 1)添加添加属性,而[]允许您直接访问该值并分配它
2) Use [] if Attributes.Contains the value, otherwise Add it 2)如果Attributes.Contains值使用[],否则添加它
3) Usually an ArgumentException will occur (An item with the same key has already been added) 3)通常会发生ArgumentException(已经添加了具有相同键的项)

One is adding an attribute, the other is referencing/setting it. 一个是添加属性,另一个是引用/设置它。

You may not want to add it if it already exists. 如果已经存在,您可能不想添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM