gpt4 book ai didi

c# - C# 中类似 VB 的自定义事件

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

Visual Basic 具有自定义事件。自定义事件的示例:https://msdn.microsoft.com/en-us/library/wf33s4w7.aspx

有没有办法在 C# 中创建自定义事件?

在我的例子中,我需要创建一个的主要原因是在第一次订阅事件时运行代码,这在目前看来是不可能的。

例如,假设我有一个按钮。如果没有订阅者,我希望此按钮被禁用(变灰),并在至少有一个订阅者时立即启用。理论上,我可以这样做——如果这种语法确实存在的话:

// internal event, used only to simplify the custom event's code
// instead of managing the invocation list directly
private event Action someevent;

// Pseudo code ahead
public custom event Action OutwardFacingSomeEvent
{
addhandler
{
if (someevent == null || someevent.GetInvocationList().Length == 0)
this.Disabled = false;
someevent += value;
}
removehandler
{
someevent -= value;
if (someevent == null || someevent.GetInvocationList().Length == 0)
this.Disabled = true;
}
raiseevent()
{
// generally shouldn't be called, someevent should be raised directly, but let's allow it anyway
someevent?.Invoke();
}
}

如果我对 VB 文章的理解正确,那么将这段代码逐行翻译成 VB,将完全符合我的要求。有什么方法可以在 C# 中完成吗?

换句话说/一个稍微不同的问题:有没有办法在订阅和取消订阅事件时运行代码?

最佳答案

您也可以通过在 C# 中定义显式事件访问器来接管事件的订阅过程。以下是示例中 someevent 事件的手动实现:

private Action someevent; // Declare a private delegate

public event Action OutwardFacingSomeEvent
{
add
{
//write custom code
someevent += value;
}
remove
{
someevent -= value;
//write custom code
}
}

关于c# - C# 中类似 VB 的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43517146/

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