Skip to main content
 首页 » 编程设计

c#之引发明确实现的事件

2024年02月13日24langtianya

考虑以下星座。

public delegate void BarHandler(Foo sender, FooEventArgs<Object> args); 
public delegate void BarHandler<T>(Foo<T> sender, FooEventArgs<T> args); 
 
public interface Foo 
{ 
    Object Value 
    { get; } 
 
    event BarHandler BarEvent; 
 
    void Update(); 
} 
 
public interface Foo<T> : Foo 
{ 
    new T Value 
    { get; } 
 
    new event BarHandler<T> BarEvent; 
} 
 
public class Baz<T> : Foo<T> 
{ 
    Object Foo.Value 
    { get { return Value; } } 
 
    public T Value 
    { get; set; } 
 
    private BarHandler handler; 
 
    event BarHandler Foo.BarEvent 
    { 
        add{ handler += value; } 
        remove{ handler -= value; } 
    } 
 
    public event BarHandler<T> BarEvent; 
 
    public void Update() 
    { 
        BarEvent(this, new FooEventArgs<T>()); 
        (this as Foo).BarEvent(this, new FooEventArgs<Object>()); 
    } 
} 

我有一个接口(interface)和一个扩展第一个接口(interface)的通用接口(interface)以及一个扩展通用接口(interface)的类。通用接口(interface)通过 new 关键字隐藏了非通用接口(interface)。 Update 方法应该引发非泛型和泛型两者。这就是我目前正在处理的问题。 产生的错误是:

The event BarEvent can only appear on the left hand side of += or -= when used outside of Foo. 

但是我在 Foo 中,还是我错过了什么?

所以,我想要的是,无论客户端在哪个事件上注册,都应该得到通知。我还应该提一下,add 和 remove 都必须有效,所以没有委托(delegate)或类似的选项。

请您参考如下方法:

只需使用私有(private) handler 变量,这应该可以解决问题。

public void Update() 
{ 
    BarEvent(this, new FooEventArgs<T>()); 
    handler(this, new FooEventArgs<Object>()); 
} 

检查 BarEvent 和 handler 是否为 null 可能也是个好主意。