从所有类外面调用C#事件? [英] Calling C# events from outside the owning class?

查看:161
本文介绍了从所有类外面调用C#事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我目前的情况是这样的:

  public class CustomForm:Form 
{
public class CustomGUIElement
{
...
public event MouseEventHandler Click ;
//等,等等。
...
}

私人列表< CustomGUIElement> _elements;

...

public void CustomForm_Click(object sender,MouseEventArgs e)
{
//我们可能要调用其中一个_elements [ n]。点击这里
//但是我们不能因为我们不在同一个类。
}
}

我的第一个想法是有一个类似于

 内部枚举GUIElementHandlers {Click,...} 
internal void CustomGUIElement :: CallHandler(GUIElementHandler h,object [ ] args){
switch(h){
case点击:
this.Click(this,(EventArgs)args [0]);
break;
... // etc等等
}
}

这是一个可怕的丑陋的污泥,但它应该工作吗?一定要有一个更优雅的解决方案呢? .NET库一直在使用消息处理程序,并在Control中调用事件。还有其他任何人有其他/更好的想法吗?

解决方案

你只需要添加一个调用事件的公共方法。微软已经为某些事件(例如执行点击)执行

  public class CustomGUIElement 
{
public void PerformClick()
{
OnClick(EventArgs.Empty);
}

protected virtual void OnClick(EventArgs e)
{
if(Click!= null)
单击(this,e);
}
}

然后,您将在示例事件处理程序中执行以下操作...

  public void CustomForm_Click(object sender,MouseEventArgs e)
{
_elements [0] .PerformClick();
}


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

My current circumstances are this:

public class CustomForm : Form
{
    public class CustomGUIElement
    {
    ...
        public event MouseEventHandler Click;
        // etc, and so forth.
    ...
    }

    private List<CustomGUIElement> _elements;

    ...

    public void CustomForm_Click(object sender, MouseEventArgs e)
    {
        // we might want to call one of the _elements[n].Click in here
        // but we can't because we aren't in the same class.
    }
}

My first thought was to have a function similar to:

internal enum GUIElementHandlers { Click, ... }
internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) {
    switch (h) {
        case Click:
            this.Click(this, (EventArgs)args[0]);
            break;
        ... // etc and so forth
    }
}

It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas?

解决方案

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();
}

这篇关于从所有类外面调用C#事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆