【发布时间】: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 的抽象。把CallMyEventimpl 放在那里。更改为MyClass : MyAbstract。 -
您只能在默认实现中执行接口的外部使用者可以执行的操作(毕竟默认实现在任何实际实现中的位置)
标签: c# .net interface default-interface-member