对象初始化程序

时间:2015-06-05 14:04:30

标签: c# asp.net

我正在重构一些旧代码,我将旧的状态图像替换为Font Awesome Icons。

我们有一个创建图像并将其返回的方法,用于动态地向页面添加控件。

旧代码

  return new Image {
      ImageUrl = SomeConstURL,
      ToolTip = tooltip
  };

新代码

  return new HtmlGenericControl
  {
      InnerHtml = IconFactory("fa-circle", UnacceptableIconClass, "fa-2x"),
      Attributes = { Keys = tooltip}
  };

当我使用上面的新代码时,我收到错误:

  

错误638属性或索引器'键'无法分配 - 它是只读的

这是一个直接的错误,它是只读的,我无法通过这种方式进行分配。

我过去曾做过:

someIcon.Attributes["title"] = "My tooltip text";

但是,当我尝试在初始化程序中执行相同操作时:

new HtmlGenericControl
     Attributes["title"] = "My tooltip text"
}

我收到错误:

  

无效的初始化成员delcrator

我根本不知道如何在初始化程序中执行此操作。

我查看了HtmlGenericControl

的文档

1 个答案:

答案 0 :(得分:1)

对象初始化器语法如下:

new Type
{
    SettableMember = Expression
    [,SettableMember2 = Expression2]...
}

SettableMember 需要成为可设置成员的位置。形式上,在C#规范中:

  

每个成员初始值设定项必须为正在初始化的对象命名可访问的字段或属性

因此,您无法一次性执行此操作,因为Attributes是具有索引器的类型的只读属性。您需要单独访问索引器,因为C类属性P的索引器访问不是C类的成员访问,因此在对象初始化程序中无效:

var control = new HtmlGenericControl
{
    InnerHtml = IconFactory("fa-circle", UnacceptableIconClass, "fa-2x"),   
};

control.Attributes["title"] = "My tooltip text";

return control;

Attributes可设置且AttributeCollection易于构建,您可以分配它:

var control = return new HtmlGenericControl
{
    InnerHtml = IconFactory("fa-circle", UnacceptableIconClass, "fa-2x"),   
    Attributes = new AttributeCollection
    {
        { "title", "My tooltip text" }
    },
};