【问题标题】:Invoke c# event inside interface在接口内调用 c# 事件
【发布时间】:2022-01-14 09:00:08
【问题描述】:

我试图在定义它的接口中调用一个事件(参见下面的代码)。 但是,我收到以下错误: Program.cs(7,3): error CS0079: The event 'IMyInterface.MyEvent' can only appear on the left hand side of += or -=.
我怀疑它可能与接口中声明的所有事件始终是属性有关。 这是一个错误、一个功能吗?是否有任何解决方法?

谢谢。

using System;
public interface IMyInterface
{
    event EventHandler? MyEvent;
    void CallMyEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

public class MyClass : IMyInterface
{
    public event EventHandler? MyEvent;
}
static class Program
{
    static void Main()
    {
        var obj = new MyClass();
        obj.CallMyEvent();
    }
}

【问题讨论】:

  • 你真的不应该在界面内这样做。
  • 你为什么要在你的界面中写实现代码?我知道这是 c# 的一个新特性,但是,为什么呢?
  • 看起来您对界面中的事件是正确的,只是添加/删除 api 没有支持字段github.com/dotnet/csharplang/discussions/2928
  • 使CallMyEvent 成为常​​规接口定义的方法。创建一个实现 IMyInterface 的抽象。把CallMyEvent impl 放在那里。更改为MyClass : MyAbstract
  • 您只能在默认实现中执行接口的外部使用者可以执行的操作(毕竟默认实现在任何实际实现中的位置)

标签: c# .net interface default-interface-member


【解决方案1】:

我认为这是因为event EventHandler? MyEvent没有在你的接口中实现,它将在你的类中实现,之后你可以Invoke它:

public class MyClass : IMyInterface
{
    public event EventHandler? MyEvent;

    public void CallMyEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

在 C# 8 之后,您实际上可以在 interface 中执行方法的默认实现,但只能是方法,而不是事件。

如果你想要预定义的方法,它会调用事件,你可以使用abstract class 而不是interface

【讨论】:

    【解决方案2】:

    似乎解决此问题的唯一方法是在界面外调用事件。要么使用我试图避免的抽象类,要么使用常规接口方法并放弃 DRY 代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2018-04-17
      • 1970-01-01
      相关资源
      最近更新 更多