Initialize the Attributes property of a WebControl object using collection initializer

女生的网名这么多〃 提交于 2019-12-06 04:52:01

问题


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" } } } } };

I get the error:

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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/38620600/initialize-the-attributes-property-of-a-webcontrol-object-using-collection-initi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!