Calling C# events from outside the owning class?

后端 未结 4 1268
广开言路
广开言路 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.

提交回复
热议问题