gpt4 book ai didi

c# - 事件订阅的最佳选择

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:30 25 4
gpt4 key购买 nike

您能告诉我创建 Activity 的最佳方式还是所有选项都不错吗?

        // OPTION 1
buttonAlert.Click += delegate
{
textChange.Text = string.Format("Hello World");
};

// OPTION 2
buttonAlert.Click +=(sender, e) =>
{
textChange.Text = string.Format("Hello World");
};

// OPTION 3
buttonAlert.Click += delegate (object sender, EventArgs e)
{
textChange.Text = string.Format("Hello World");
};

最佳答案

这只是一个偏好问题。在性能方面都是等效的。

因此,请根据您的需要和喜好进行选择。

作为我回答的补充,我想提醒您必须在订阅 (+=) 之后取消订阅事件 (-=)。

来自documentation :

To prevent your event handler from being invoked when the event is raised, simply unsubscribe from the event. In order to prevent resource leaks, it is important to unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.

关于c# - 事件订阅的最佳选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154964/

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