简体   繁体   中英

Why can't I directly access the properties of a custom object that I've assigned to a WinForms Control.Tag property?

I want to set a Winforms Control.Tag property with my custom object ButtonMetaData and then access the properties of ButtonMetaData using the Control.Tag property. Should work because the Tag property is defined as an object, right? See Figure 1.

However, in order to access the properties of ButtonMetaData , I'm forced to assign the Tag object to an intermediate object variable ( x in my example) in order to access the ButtonMetaData properties. When I try and access them using the Tag object that has been cast to ButtonMetaData , the compiler complains. See Figure 2.

Why can't I directly access the properties of ButtonMetaData using the Tag object that has been cast to ButtonMetaData ?

Figure 1

图1

Figure 2

public class ButtonMetaData
{
    public bool clickedByUser;
    public bool clickedProgramatically;

    public ButtonMetaData(bool clickedByUser, bool clickedProgramatically)
    {
        this.clickedByUser = clickedByUser;
        this.clickedProgramatically = clickedProgramatically;
    }
}

private void Button1_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;

    button.Tag = new ButtonMetaData(clickedByUser: true, clickedProgramatically: false);

    //BUILDS OK
    ButtonMetaData x = (ButtonMetaData)button.Tag;
    Console.WriteLine(x.clickedByUser);
    Console.WriteLine(x.clickedProgramatically);
    //BUILDS OK

    //DOESN'T BUILD - error on field clickedByUser and error on field clickedProgramatically
    Console.WriteLine((ButtonMetaData)button.Tag.clickedByUser);
    Console.WriteLine((ButtonMetaData)button.Tag.clickedProgramatically);
    //DOESN'T BUILD - error on field clickedByUser and error on field clickedProgramatically

}

You forgot some brackets. You need to cast button.Tag to ButtonMetaData . Try this:

 Console.WriteLine(((ButtonMetaData)button.Tag).clickedByUser);

Without brackets you are casting button.Tag.clickedByUser to ButtonMetaData ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM