1

I am talking in the context of event handler in a C# windows forms, but I'm assuming the answer could be used anywhere in C#.

To give an example, I have a form that has many check boxes that each activate a button. The CheckedChanged event is handled by a function that is very similar for each CheckBox and it looks something like this right now:

private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
    int uniquetocheckbox = 12345;

    if(acheckbox.CheckedChanged)
    {
          ThisFunction(uniquetocheckbox, true);
          AssociatedButton.Enabled = true;
    }
    else
    {
          ThisFunction(uniquetocheckbox, false);
          AssociatedButton.Enabled = false;
    }  
}

There are a lot of these check boxes and I'm trying to cut and past the code for each and make as few changes as possible so I want to do something like this :

private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
    int uniquetocheckbox = 12345;

    if((CheckBox)sender.Checked)  //CHANGE HERE
    {
          ThisFunction(uniquetocheckbox, true);
          AssociatedButton.Enabled = true;
    }
    else
    {
          ThisFunction(uniquetocheckbox, false);
          AssociatedButton.Enabled = false;
    }  
}

This does not work. The easy work around is this :

private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
    int uniquetocheckbox = 12345;
    CheckBox cb = (CheckBox)sender;

    if(cb.Checked)  //CHANGE HERE
    {
          ThisFunction(uniquetocheckbox, true);
          AssociatedButton.Enabled = true;
    }
    else
    {
          ThisFunction(uniquetocheckbox, false);
          AssociatedButton.Enabled = false;
    }  
}

But out of pure curiosity I am wondering if there is a way to do it in one line like the second example I gave. I would like to know because I think it looks better and is obviously 1 line shorter.

4

6 回答 6

7

我认为您只是缺少一组括号。您要转换为Checkbox,然后获取其属性:

if (((CheckBox)sender).Checked)

这将强制操作的顺序首先转换,然后从转换结果中获取属性。

于 2013-07-03T20:53:28.890 回答
3

Sure, it's possible. You just missed another set of brackets:

if(((CheckBox)sender).Checked)

However, I wouldn't do this. Why? You don't want to cast again if you want to access the sender as a textbox again if you did it your way.

于 2013-07-03T20:53:40.903 回答
2

你可以。例如:

object o;
o = new SomeType();
var prop = ((SomeType)o).SomeProperty;
于 2013-07-03T20:54:52.717 回答
1

它需要是这样的:

if(((CheckBox)sender).Checked)  //CHANGE HERE

但就我个人而言,我更喜欢你表现得更好的方式。这样,如果它需要再次铸造,它已经完成了。

于 2013-07-03T20:55:17.063 回答
1

不知道任何 C# 但((CheckBox)sender).Checked)应该可以工作。在java中的“。” (成员访问)具有比强制转换更高的优先级,因此像这样放置括号应该会强制强制转换首先发生。

于 2013-07-03T20:55:23.390 回答
0

您只需要在声明中添加几个括号if

if (((CheckBox)sender).Checked)
{
    ...
}
于 2013-07-03T20:53:27.733 回答