gpt4 book ai didi

c# - 我应该创建一个新方法来处理事件还是重写基本方法?

转载 作者:太空狗 更新时间:2023-10-29 23:43:47 25 4
gpt4 key购买 nike

在使用 C# 编写 UWP 程序时,我正在使用从 UIElement 类派生的类,我想在其中包含处理输入控件,例如鼠标和键盘操作。现在我看到已经有虚拟方法说 OnSomeEvent() 显然我可以覆盖这些方法以适合我的处理过程,或者我可以创建新方法 处理基类中定义的公共(public)事件,并在构造函数中订阅这些输入事件。我假设这两种方法都有效,但我希望知道哪种方法更专业或更可取,以及原因。这也有助于解释为什么 MS 同时提供这两种方式。

这是 UIElement 类的事件和方法 https://msdn.microsoft.com/en-us/library/system.windows.uielement(v=vs.110).aspx#Examples

和一段引用

UIElement provides a starting point for element layout characteristics, and also exposes virtual methods that derived classes can override, which can influence the layout rendering behavior of the element and its child elements. Much of the input and focusing behavior for elements in general is also defined in the UIElement class. This includes the events for keyboard, mouse and stylus input, and related status properties. Many of these events are routed events, and many of the input-related events have both a bubbling routing version as well as a tunneling version of the event. These paired events are typically the events of greatest interest to control authors.

最佳答案

在派生类中,我通常会覆盖现有的方法。

为什么?事件处理程序不如覆盖方法可靠。例如,外部类可以清除事件处理程序,但不能更改覆盖中的代码。不过,您必须密封自己的类,否则您的方法可能会被覆盖。

要考虑的另一点是:我是否要更改控件的工作方式?我是否必须控制代码的确切执行时刻(比方说在基类代码之前、之后或代替)?如果是这样,您必须使用覆盖。

关于c# - 我应该创建一个新方法来处理事件还是重写基本方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40572700/

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