Calling C# events from outside the owning class?

后端 未结 4 1262
广开言路
广开言路 2020-12-17 15:30

Is it possible under any set of circumstances to be able to accomplish this?

My current circumstances are this:

public class CustomForm : Form
{
             


        
相关标签:
4条回答
  • 2020-12-17 16:09

    The event keyword in c# modifies the declaration of the delegate. It prevents direct assignment to the delegate (you can only use += and -= on an event), and it prevents invocation of the delegate from outside the class.

    So you could alter your code to look like this:

    public class CustomGUIElement
    {
    ...
        public MouseEventHandler Click;
        // etc, and so forth.
    ...
    }
    

    Then you can invoke the event from outside the class like this.

    myCustomGUIElement.Click(sender,args);
    

    The drawback is that code using the class can overwrite any registered handlers very easily with code like this:

    myCustomGUIElement.Click = null;
    

    which is not allowed if the Click delegate is declared as an event.

    0 讨论(0)
  • 2020-12-17 16:17

    You can shorten the code suggested in the accepted answer a lot using the modern syntax feature of the .NET framework:

    public event Action<int> RecipeSelected;
    public void RaiseRecpeSelected(int recipe) => RecipeSelected?.Invoke(recipe);
    
    0 讨论(0)
  • You just need to add a public method for invoking the event. Microsoft already does this for some events such as PerformClick for controls that expose a Click event.

    public class CustomGUIElement    
    {
        public void PerformClick()
        {
            OnClick(EventArgs.Empty);
        }
    
        protected virtual void OnClick(EventArgs e)
        {
            if (Click != null)
                Click(this, e);
        }
    }
    

    You would then do the following inside your example event handler...

    public void CustomForm_Click(object sender, MouseEventArgs e)        
    {
        _elements[0].PerformClick();
    }
    
    0 讨论(0)
  • 2020-12-17 16:30

    You really should wrap the code you want to be able to execute from the outside in a method. That method can then do whatever your event would do - and that event would also instead call that method.

    0 讨论(0)
提交回复
热议问题