我真的不明白这段代码有什么问题。它正在抛出几个错误:
错误CS0079:事件
core.Events.Event.thisEvent只能出现在+=或-=运算符的左侧。 错误CS0070:事件core.Events.Event.thisEvent只能在+=或-=类型之外使用时出现在core.Events.Event的左侧。 错误CS1502:System.Delegate.Combine(System.Delegate, System.Delegate)的最佳重载方法匹配有一些无效的参数 错误CS1503:参数#1不能将object表达式转换为System.Delegate类型
我做错了什么,我怎么解决这个问题?
using System;
using System.Runtime.CompilerServices;
namespace core.Events
{
public class Event
{
public delegate void EventDelegate (object from,EventArgs args);
public event Event.EventDelegate thisEvent {
[MethodImpl(MethodImplOptions.Synchronized)]
add {
this.thisEvent += (Event.EventDelegate)Delegate.Combine (this.thisEvent, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove {
this.thisEvent -= (Event.EventDelegate)Delegate.Remove (this.thisEvent, value);
}
}
public void call (object from, EventArgs args)
{
this.thisEvent (from, args);
}
}
}提前谢谢你的帮助,我想我只是太累了,迷失了来源.
发布于 2012-07-24 23:28:27
这是一种类似于在属性的getter中使用属性名称的错误。这通常是造成这种错误的原因,但这一错误被过早地抓住了。您需要创建一个私有备份字段来存储委托,当您显式地编写访问器时,编译器将不再自动为您生成它。因此:
private EventDelegate eventImpl;
public event Event.EventDelegate thisEvent {
[MethodImpl(MethodImplOptions.Synchronized)]
add {
this.eventImpl += value;
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove {
this.eventImpl -= value;
}
}
public void call(object from, EventArgs args) {
var handler = this.eventImpl;
if (handler != null) handler(from, args);
}注意,调用()实现,如果没有人订阅事件,它就会避免崩溃,而当线程取消订阅事件时,会避免另一次崩溃。并且我使用了简短的表示法来避免显式调用Delegate.Combine()。请注意,如果不使用访问器,这段代码实际上与编译器自动生成的代码并没有什么不同。
https://stackoverflow.com/questions/11627736
复制相似问题