使用集合初始化程序初始化WebControl对象的Attributes属性 [英] Initialize the Attributes property of a WebControl object using collection initializer
问题描述
我想内联初始化WebControl
对象,但是对于某些字段,这有点棘手.例如,当我尝试初始化的Attributes
属性时TextBox
对象是这样的:
I want to initialize WebControl
objects, inline, but for some fields this is a little bit tricky. For instance when I try to initialize the Attributes
property of a TextBox
object like this:
using System.Web.UI.WebControls;
Panel panel = new Panel() { Controls = { new TextBox() { Attributes = { { "key", "value" } } } } };
我得到了错误:
无法使用集合初始化类型' AttributeCollection ' 初始化程序,因为它没有实现 'System.Collections.IEnumerable'
Cannot initialize type 'AttributeCollection' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
任何想法在这种情况下内联初始化如何工作?
Any idea how could inline initialization work in this case ?
推荐答案
您可以执行此操作,但如果使用的是C#6.这称为索引初始化,因此请尝试以下代码,但是正如我所说的,这在Visual Studio 2015和C#6中应该可以正常工作:
You can do this but if you use C#6. This is called index initialization so try the following code but as I said this should works fine in Visual Studio 2015 and C#6:
Panel panel = new Panel
{
Controls =
{
new TextBox
{
Attributes =
{
["readonly"] = "true",
["value"] = "Hi"
}
}
}
};
The old collection initializers (Prior to C#6) only works with types that implement IEnumerable<T>
and have an Add
method. But now any type with an indexer will allow initialization via this syntax.
这篇关于使用集合初始化程序初始化WebControl对象的Attributes属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!