C# finding sender

坚强是说给别人听的谎言 提交于 2019-12-12 19:11:24

问题


private void buttonCheck(object sender, EventArgs e)
{
   Type x = sender.GetType();
   var y = Activator.CreateInstance(x); //sends me back to the original problem : sender is an object, not a usable object.

   var x = (Button)sender;  // == button, but you never know what sender is until it's already in this function... so 
   dynamic z = sender; //gives you the image of sender i'm looking for, but it's at runtime, so no intellisense/actual compiletime knowledge of what sender is.
}

how do you go about creating a usable instance of sender without prior knowledge of the class sender is actually bringing to this method?


回答1:


In the vast majority of cases you know what control(s) will be firing the event because you (the programmer) wire them up. For example, if you wire this event up to a button (or even multiple buttons), You know the sender is a Button so you can just cast:

var b = sender as Button;

or

var b = (Button)sender;

either one will give you full intellisense.

If you wire up this event to multiple control types, your best bet is to check each possible type:

if(sender is Button)
//  cast to Button
else if (sender is TextBox)
//  cast to TextBox
else is (sender is CobmoBox)
//  cast to ComboBox

It may seem messy, but since you haven't stated what you actually want to do in the event handler that's the cleanest way in one event to handle multiple possible sender types.

Another option would be to just create multiple event handlers (one for each type) and wire them up to their respective types. I can't think of many code-reuse scenarios between a Button and a TextBox.




回答2:


I think dynamic keyword is what you are looking for. At compile time compiler assumes that there is Text property in btn.

  private void button1_Click(object sender, EventArgs e)
  {
     var btn = (dynamic)sender;

     string text = btn.Text;
  }



回答3:


Here's a DataBindingComplete variation that clears the default selection from the DataGridView control. I've got numerous DataGridView controls across multiple tabs and only need this one event handler for all of them which is fantastic. This is based off the response from VladL so all credit should go to them.

    private void Dynamic_DataBindingComplete(Object sender, DataGridViewBindingCompleteEventArgs e)
    {
        var control = (dynamic) sender;
        control.ClearSelection();
    }


来源:https://stackoverflow.com/questions/14111512/c-sharp-finding-sender

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!