简体   繁体   中英

C# Need help understanding strange Lambda construct

Today I ran into this piece of code in ac# project:

public partial class LoginView : UserControl
    {
        public LoginView()
        {
            this.InitializeComponent();
            this.Loaded += (s, e) => this.user.Focus();
        }
     ...
    }

this.Loaded is declared

public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);

Ok, so we can add a event handler code taking two parameters, a sender s of type object and a RoutedEventArgs e. What actually is assigned is

public bool Focus ();

which seems to me to be a function taking no parameters and returning a boolean.

The code does obviously work, and I think I understand what it does (focus a textbox named "user" if this.loaded fires) but why is this code valid?

Thnx,

Armin.

You're not assigning the Focus method to the Loaded delegate. What the code is actually doing, is assigning a lambda to that delegate which conforms to the delegate definition.

The code

 this.Loaded += (s, e) => this.user.Focus();

is actually a shorthand for this:

 this.Loaded += new RoutedEventHandler(FocusSomething);

and the FocusSomething method in the snippet above would be declared as

public void FocusSomething(object sender, RoutedEventArgs args)
{
    this.user.Focus();
}

You're just 'ignoring' the return value of the Focus method, but the method that is assigned to the delegate has a void return type and accepts the 2 parameters (object and RoutedEventArgs so that's just valid).

So the .Loaded event does provide two parameters, but there is no requirement to use them in your lambda. Depending on how your code is formatted they can be safely ignored. In the same vein, while the Focus() method does return a value, there is no requirement to use it anywhere. It's not very defensive and odds are the implementer provided the value for a reason, but strictly speaking it's not required from a language perspective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM