c# - 引发类型实现接口(interface)的对象的事件

标签 c# .net events interface

我在尝试引发一个对象的事件时遇到问题,其中类型实现了另一个类的接口(interface)(事件所在的地方)。

这是我的代码:

界面 IBaseForm

public interface IBaseForm
{
    event EventHandler AfterValidation;
}

实现接口(interface) IBaseForm 的 Form

public partial class ContactForm : IBaseForm
{
    //Code ...

    public event EventHandler AfterValidation;
}

我的 Controller : 这里是错误发生的地方

错误信息:

The event AfterValidation can only appear on the left hand side of += or -=(except when used from whithin the type IBaseForm)

public class MyController
{
    public IBaseForm CurrentForm { get; set; }

    protected void Validation()
    {
        //Code ....

        //Here where the error occurs
        if(CurrentForm.AfterValidation != null)
            CurrentForm.AfterValidation(this, new EventArgs());
    }
}

提前致谢

最佳答案

您不能从定义类之外引发事件。

您需要在您的界面上创建一个 Raise() 方法:

public interface IBaseForm
{
    event EventHandler AfterValidation;

    void RaiseAfterValidation();
}

public class ContactForm : IBaseForm
{
    public event EventHandler AfterValidation;

    public void RaiseAfterValidation()
    {
        if (AfterValidation != null)
            AfterValidation(this, new EventArgs());
    }
}

在你的 Controller 中:

protected void Validation()
{
    CurrentForm.RaiseAfterValidation();
}

但如果您想从定义类之外触发事件,这通常是一种设计味道......通常应该在触发事件的 IBaseForm 实现中有一些逻辑。

关于c# - 引发类型实现接口(interface)的对象的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075832/

相关文章:

c# - xUnit - 显示理论成员数据的测试名称 (TestCase)

c# - 如何序列化 Nullable<bool>?

c# - 上传亚马逊s3后获取文件网址

c# - 如何从域模型中的内部服务类通知进度

c# - c# 中是否有等效的 c++ vector::back

c# - 调用基类静态方法时获取调用者派生类

c# - 将像素转换为点

php - Symfony2 在内核请求事件中抛出 404

.net - 领域事件设计模式

c# - 从字节数组创建 BitmapImage