简体   繁体   English

C#CS0079事件处理编译错误

[英]C# CS0079 Event Handling Compile Error

I got CS0079 compile error when I tried to run the code below: 我尝试运行以下代码时遇到CS0079编译错误:

public delegate void MyClassEHandler(MyClassEParam param);

public class MyClassE
{
    public static event MyClassEHandler Error
    {
         add
         {
              MyClassE.Error = (MyClassEHandler)Delegate.Combine(MyClassE.Error, value);
         } 
    }
}

Error: 错误:

CS0079 : The event MyClassE.Error can only appear on the left hand side of += or -= CS0079:事件MyClassE.Error只能出现在+ =或 - =的左侧

Searched around but couldn't figure out how to resolve it. 搜索过但无法弄清楚如何解决它。

ADDED: if (MyClass.Error != null) or MyClass.Error(null, null); ADDED:if(MyClass.Error!= null)或MyClass.Error(null,null);

Get the same CS0079 error. 得到相同的CS0079错误。

CS0079 : The event MyClassE.Error can only appear on the left hand side of += or -= CS0079:事件MyClassE.Error只能出现在+ =或 - =的左侧

Can anyone help me on this? 谁可以帮我这个事?

You cannot set an event, you can just add or remove handlers on it. 您无法设置事件,只需在其上添加或删除处理程序即可。 So, as the error says, you should just do: 所以,正如错误所说,你应该这样做:

public delegate void MyClassEHandler(MyClassEParam param);

public static event MyClassEHandler Error
{
     add
     {
          MyClassE.Error += value;
     } 
     remove         
     {
          MyClassE.Error -= value;
     } 
}

and the Delegate.Combine will work magically for you. 而且Delegate.Combine会为你神奇地工作。

Try this 试试这个

public delegate void MyClassEHandler(MyClassEParam param);  
static MyClassEHandler error;

public static event MyClassEHandler Error
{
 add
 {
      MyClassE.error += (MyClassEHandler)Delegate.Combine(MyClassE.Error, value);
 } 

 remove
 {
      MyClassE.Error -= (MyClassEHandler)Delegate.Combine(MyClassE.Error, value);
 } 

}

Refer to the Intercepting add remove of c# event and delegates 请参阅拦截添加删除c#事件和委托

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM