gpt4 book ai didi

c# - C#中如何订阅其他类(class)的事件?

转载 作者:IT王子 更新时间:2023-10-29 04:47:46 28 4
gpt4 key购买 nike

一个简单的场景:一个引发事件的自定义类。我希望在表单中使用此事件并对其使用react。

我该怎么做?

请注意,表单和自定义类是单独的类。

最佳答案

public class EventThrower
{
public delegate void EventHandler(object sender, EventArgs args) ;
public event EventHandler ThrowEvent = delegate{};

public void SomethingHappened() => ThrowEvent(this, new EventArgs());
}

public class EventSubscriber
{
private EventThrower _Thrower;

public EventSubscriber()
{
_Thrower = new EventThrower();
// using lambda expression..could use method like other answers on here

_Thrower.ThrowEvent += (sender, args) => { DoSomething(); };
}

private void DoSomething()
{
// Handle event.....
}
}

关于c# - C#中如何订阅其他类(class)的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913374/

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