Connection of C# event handlers: delegate inference and explicit delegate usage
Events in C# allow loose coupling between objects and provide a mechanism for handling external events. A common scenario involves dynamically subscribing to events from an external object, for which you will encounter the following syntax variation:
<code class="language-c#">[object].[event] += anEvent;</code>
or
<code class="language-c#">[object].[event] += new EventHandler(anEvent);</code>
Both methods look similar, but a deeper understanding reveals their subtle differences.
In the first variant, the compiler performs delegate inference to automatically determine the appropriate delegate type based on the provided function signature. This simplified syntax minimizes code redundancy.
In the second variant, you explicitly specify the new
delegate using the EventHandler
keyword. This approach was the only option for C# 1.0 projects, but in C# 2.0 and later, delegate inference becomes the preferred approach.
When to use delegate inference
For C# 2.0 and higher projects, delegate inference is recommended. It is concise and improves the readability of the code.
Example:
<code class="language-c#">private void Button1_Click(object sender, EventArgs e) { // 事件处理逻辑 } private void Form1_Load(object sender, EventArgs e) { Button1.Click += Button1_Click; }</code>
In this example, delegate inference automatically determines the correct Button1
delegate for the EventHandler
click event.
Explicit delegate usage
While delegate inference is common, when dealing with legacy code or performing performance optimizations, it may sometimes be necessary to specify delegates explicitly. However, explicit delegate usage often adds unnecessary verbosity and should be used only when necessary.
The above is the detailed content of EventHandler Wiring in C#: Delegate Inference vs. Explicit Delegate Usage?. For more information, please follow other related articles on the PHP Chinese website!