简体   繁体   English

如何在C#中实现抽象事件或接口方法事件?

[英]How do I implement an abstract event or interface method event in C#?

My base interface IFoo declares 我的基本接口IFoo声明

event EventHandler Changed

when I do 'implement interface' I get some lame boilerplate code but how do I provide a decent default implementation? 当我执行“实现接口”时,我得到了一些me脚的样板代码,但是如何提供一个不错的默认实现?

add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }

How does the interface declare the event with the interface name prefixed on the event name? 接口如何用事件名称前缀的接口名称声明事件? I'm not sure that's legal C#. 我不确定这是合法的C#。

If you can get away without the "IFoo." 如果没有“ IFoo”就可以逃脱。 prefix, just declare the event in your class and let the compiler create the default add/remove handers for you. 前缀,只需在类中声明事件,然后让编译器为您创建默认的添加/删除处理程序。 All you should have to worry about is when to trigger the event: 您只需要担心何时触发事件:

interface IFoo
{
    event EventHandler OnChanged;
}

class MyClass : IFoo
{
    public event EventHandler OnChanged;

    private FireOnChanged()
    {
        EventHandler handler = this.OnChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty); // with appropriate args, of course...
        }
    }
}

... Or did I misunderstand about where you're inheriting the event from? ...还是我误会了您从哪里继承事件? is your class derived from an abstract base class which in turn implements an interface (which declares the event)? 您的类是从抽象基类派生的,该抽象基类又实现了一个接口(用于声明事件)? That could be what you mean, but it wasn't clear in the question. 那可能就是您的意思,但问题尚不清楚。

private EventHandler onChanged;

event EventHandler IFoo.OnChanged
{
    add
    {
        onChanged += value;
    }
    remove
    {
        onChanged -= value;
    }
}

I recommend you change the name of the event to conform with common naming standards of events. 我建议您更改事件的名称以符合事件的通用命名标准。 In this case Changed. 在这种情况下已更改。 Link to previous post 链接到上一篇文章

   private System.EventHandler _Changed;

    private readonly object _EventLock = new object();

    public event System.EventHandler Changed {
        add {
            lock (_EventLock) {
                _Changed += value;
            }
        }
        remove {
            lock (_EventLock) {
                _Changed -= value;
            }
        }
    }

    protected virtual void OnChanged(System.EventArgs args) {

        System.EventHandler handler = _Changed;
        if (handler != null) {
            handler(this, args);
        }
    }

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

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