对象初始化程序中的HtmlGenericControl属性 [英] HtmlGenericControl Attributes in Object Initializer

查看:97
本文介绍了对象初始化程序中的HtmlGenericControl属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm refactoring some of our old code, I'm replacing our old status images as Font Awesome Icons.

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

We have a method that creates an image and returns it, for dynamically adding controls to a page.

旧代码

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

新代码

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

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

When I use the above new code I get the error:

错误638属性或索引器'键'不能分配给它-只读的

Error 638 Property or indexer 'Keys' cannot be assigned to -- it is read only

这是一个直接的错误,它是只读的,我不能这样分配.

It's a straight forward error, it's read only, I can't assign it that way.

我过去曾经这样做过:

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

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

However when I try and do the same inside the initializer:

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

我得到了错误:

无效的初始值设定项成员delcarator

Invalid initializer member delcarator

我只是不知道如何在初始化程序中执行此操作.

I just have no idea how to do this in the initializer.

我查看了推荐答案

对象初始值设定项语法如下:

Object initializer syntax is like this:

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

SettableMember 需要成为可设置成员的位置.正式地,在C#规范中:

Where SettableMember needs to be a settable member. Formally, in the C# specification:

每个成员初始化程序都必须命名正在初始化的对象的可访问字段或属性

所以您不能一one而就,因为 Attributes 是带有索引器的类型的只读属性.您需要单独访问索引器,因为对类C的属性P的索引器访问不是对类C的成员访问,因此在对象初始化器中无效:

So you can't do this in one go, as Attributes is a read-only property of a type with an indexer. You need to access the indexer separately, as an indexer access of a property P of class C isn't a member access of class C and thus invalid in an object initializer:

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

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

return control;

可轻松构造 Attributes AttributeCollection ,您可以为其分配:

Were Attributes settable and AttributeCollection easily constructable, you'd be able to assign it:

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

这篇关于对象初始化程序中的HtmlGenericControl属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆