gpt4 book ai didi

C# 事件作为方法中的参数

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:26 24 4
gpt4 key购买 nike

我想在我的方法中使用事件本身。是否可以?“PlayWithEvent”方法可以使用“EventSource.Test”事件作为参数吗?

public class EventSource
{
public event EventHandler Test;
}

class Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src.Test);
}

static void PlayWithEvent (EventHandler e)
{
e (null, null);
}
}

我想要类似这样的语法:

class Program
{
static void Main(string[] args)
{
EventSource src = new EventSource ();
PlayWithEvent (src.Test);
}

static void PlayWithEvent (event e)
{
e += something;
}
}

最佳答案

您的代码无法编译——您只能从与事件相同的类中访问该事件的 EventHandler 委托(delegate),即使那样它也将是 null除非您实际添加一个事件处理程序来调用。

关于C# 事件作为方法中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695212/

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