【问题标题】:Initialize the Attributes property of a WebControl object using collection initializer使用集合初始化器初始化 WebControl 对象的 Attributes 属性
【发布时间】:2016-07-27 18:28:08
【问题描述】:

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

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

我得到错误:

无法使用集合初始化类型“AttributeCollection” 初始化器,因为它没有实现 'System.Collections.IEnumerable'

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

【问题讨论】:

  • 您的问题听起来类似于this one,并且接受的答案说这是不可能的。

标签: c# asp.net initialization collection-initializer


【解决方案1】:

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

Panel panel = new Panel
{
    Controls =
    {
        new TextBox
        {
            Attributes =
            {
                ["readonly"] = "true",
                ["value"] = "Hi"
            }
        }
    }
}; 

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

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 2013-02-24
    • 2016-01-12
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2010-09-25
    相关资源
    最近更新 更多