=>symbol meaning

=> There are two main functions, one restricts the attribute state, and the other simplifies anonymous delegation and Lambda


Usage 1: Define read-only properties

public class ManPeople {     public string Sex => "男";

    public string Name { get; set; }}

public class WomanPeople {    public string Sex => "女";

    public string Name { get; set; }}

public string Sex => "男";

The usage of => here is equivalent to { get; } = that is: set the Sex field as a read-only attribute and assign a value at the same time.

public string Sex { get;  } = "男"


Usage 2: Lambda expression, anonymous delegate

For example, define a delegate:
delegate int DeMethod(int a, int b);
define another method:
int Add(int a, int b)
{ return a + b; } I may need to call the method through the delegate like this: DeMethod m += Add; Console. WriteLine(m(2, 3));





Anonymous method syntax using C# 2.0:
DeMethod m += delegate(int a, int b) { return a + b; };
Console.WriteLine(m(2, 3));


Using C#3.0 Lambda expression:
DeMethod m += (a ,b) => a + b;
Console.WriteLine(m(2, 3));
can save the method definition.
In fact, lambda expressions just simplify the syntax of anonymous methods.


Finally, what do these characters += (s, e) => mean in C#

public MainWindow()

{

InitializeComponent();

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

this.Unloaded += (s, e) => this.Value= null;

}

In the above code, += is to add a delegation to the delegation chain, (s,e) => is a lambda expression, this expression creates a delegation, and the main body of the delegation processing is the part after =>.

In fact, this is equivalent to

this.Loaded += new EventHandler(Form_Loaded);

private void Form_Loaded(object sender,   EventArgs e) {
    InitSomeConfig ();
}

Guess you like

Origin blog.csdn.net/weixin_53163894/article/details/132684276