0

我真的不明白这段代码有什么问题。它抛出了几个错误:

错误 CS0079:事件只能出现在or运算符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);
        }
    }
}

预先感谢您的帮助,我想我只是超级累了,迷失在源头上...

4

1 回答 1

2

这与在属性的 getter 中使用属性名称类似的错误。这通常会导致 SO,但是这个错误很早就被发现了。您需要创建一个私有支持字段来存储委托,当您显式编写访问器时,编译器不再为您自动生成它。因此:

    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);
    }

注意 call() 实现,如果没有人订阅事件,它会避免崩溃,而当线程取消订阅事件时,它会避免另一个崩溃。我使用了快捷符号来避免显式调用 Delegate.Combine()。请注意,如果您不使用访问器,此代码实际上与编译器自动生成的代码并没有什么不同。

于 2012-07-24T23:28:27.443 回答