我在尝试引发一个对象的事件时遇到问题,其中类型实现了另一个类的接口(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/