Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c# - HtmlGenericControl Attributes in Object Initializer

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.

Old Code

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

New Code

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

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

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.

I've done it in the past with:

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

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

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

I get the error:

Invalid initializer member delcarator

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

I've looked at the docs for HtmlGenericControl

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object initializer syntax is like this:

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

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

Each member initializer must name an accessible field or property of the object being initialized

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;

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...