C#CS0079事件处理编译错误 [英] C# CS0079 Event Handling Compile Errors
问题描述
我无法编译以下代码.
编译错误CS0079:"CustomEvent"事件只能出现在+ =或-=
if (CustomEvent != null) //CS0079
CustomEvent(null, null); //CS0079
我该如何进行这项工作?
How can I make this work?
我的实现是这样的:
public delegate void EventHandler(object sender, EventArgs e);
public static event EventHandler CustomEvent
{
add { CustomEvent += value; }
remove { CustomEvent -= value; }
}
private static void Func()
{
if (CustomEvent != null) //CS0079
CustomEvent(null, null); //CS0079
}
推荐答案
您的编辑显示了一个递归调用:您正在声明一个自定义事件,这意味着您旨在提供一个后备字段;例如:
Your edit shows a recursive call: you are declaring a custom event, which means you are meant to provide a backing field; for example:
private static EventHandler customEvent;
public static event EventHandler CustomEvent
{
add { customEvent += value; }
remove { customEvent -= value; }
}
private static void Func()
{
var tmp = customEvent;
if (tmp != null) tmp(null, null);
}
请注意,在 Func
中,我指的是 字段 ( customEvent
),而不是事件 ( CustomEvent
).
Note that in Func
I am referring to the field (customEvent
), not the event (CustomEvent
).
但是,作为类似字段的事件,此方法更简单(线程安全)更好:
However, this is simpler are better (thread-safe) as a field-like event:
public static event EventHandler CustomEvent;
private static void Func()
{
var tmp = CustomEvent;
if (tmp != null) tmp(null, null);
}
类似字段的事件使用 event
关键字,但忽略访问器:编译器为您添加了很多样板(支持字段,并且线程安全添加/删除实现).此外,它允许通过事件名称(从声明类型)通过事件名称访问提交的后备文件,因此行 var tmp = CustomEvent;
的工作方式.
A field-like event uses the event
keyword, but omits the accessors: the compiler adds a lot of boilerplate for you (a backing field, and thread-safe add/remove implementations). Further, it allows access to the backing filed via the event name (from the declaring type), hence how the line var tmp = CustomEvent;
works.
也:对静态事件要非常小心;它们是意外保留许多物体的好方法.
Also: be very careful with static events; they are a great way to accidentally keep lots of objects alive.
这篇关于C#CS0079事件处理编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!