gpt4 book ai didi

c# - 如何在 C# 中实现抽象事件或接口(interface)方法事件?

转载 作者:太空宇宙 更新时间:2023-11-03 19:33:43 25 4
gpt4 key购买 nike

我的基础接口(interface) IFoo 声明

event EventHandler Changed

当我执行“实现接口(interface)”时,我得到了一些蹩脚的样板代码,但我如何提供合适的默认实现?

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

最佳答案

接口(interface)是如何声明事件名称前面加上接口(interface)名称的事件的?我不确定这是合法的 C#。

如果你不用“IFoo”就可以逃脱。前缀,只需在您的类中声明事件并让编译器为您创建默认的添加/删除处理程序。您只需要担心什么时候触发事件:

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...
}
}
}

... 还是我误解了您从哪里继承事件?你的类是从一个抽象基类派生出来的,而这个基类又实现了一个接口(interface)(它声明了事件)?这可能是你的意思,但问题中并不清楚。

关于c# - 如何在 C# 中实现抽象事件或接口(interface)方法事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3314711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com