使用集合初始值设定项初始化WebControl对象的Attributes属性

Chr*_*ris 4 c# asp.net initialization collection-initializer

我想初始化WebControl对象,内联,但对于某些字段,这有点棘手.例如,当我尝试初始化对象的Attributes属性时,TextBox如下所示:

using System.Web.UI.WebControls;
Panel panel = new Panel() { Controls = { new TextBox() { Attributes = { { "key", "value" } } } } };
Run Code Online (Sandbox Code Playgroud)

我收到错误:

无法初始化类型" AttributeCollection与集合初始化",因为它没有实现"System.Collections.IEnumerable"

知道在这种情况下内联初始化如何工作?

Sal*_*ari 5

你可以这样做但是如果你使用C#6.这称为索引初始化,所以尝试下面的代码,但正如我所说,这应该在Visual Studio 2015和C#6中正常工作:

Panel panel = new Panel
{
    Controls =
    {
        new TextBox
        {
            Attributes =
            {
                ["readonly"] = "true",
                ["value"] = "Hi"
            }
        }
    }
}; 
Run Code Online (Sandbox Code Playgroud)

旧的集合初始值设定项(在C#6之前)仅适用于实现IEnumerable<T>并具有Add方法的类型.但是现在任何带有索引器的类型都允许通过这种语法进行初始化.