" Mean in a Property or Method?When encountered with code such as the following:public int MaxHealth => Memory[Address].IsValid..."/> " Mean in a Property or Method?When encountered with code such as the following:public int MaxHealth => Memory[Address].IsValid...">
Home >Backend Development >C++ >What Does `=>` Mean in C# Expression-Bodied Members?
` Mean in C# Expression-Bodied Members? " />
When encountering the following code:
It is important to understand that this is not Lambda expression, but a member of an expression.
<code class="language-csharp">public int MaxHealth => Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;</code>Member of the expression
When the compiler encounters a member of the expression body, it will convert it to a getter:
Members of the expression body and fields with initialization device
<code class="language-csharp">public int MaxHealth { get { return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0; } }</code>The difference between the expression of the expression and the fields with the initialization device can be explained by comparing the following content:
The expression of the expression is a getter that calls it every time you access the attribute. On the other hand, the field is initialized once when instantiated.
Grammar candy
<code class="language-csharp">// 表达式体成员属性 public int MaxHealth => x ? y : z;</code>
<code class="language-csharp">// 带有字段初始化器的字段 public int MaxHealth = x ? y : z;</code>
The members of the expression are pure grammar sugar, and there is no additional function except the existing function. They provide the following content with a simpler syntax to attribute members:
No Return statement (hidden return expression)
No sentence block (the main body is a single expression)No need to "get" keywords (hidden by the grammar of the expression of the expression)
They are not suitable for nested types, events or fields. Although they are similar to lambda expressions in "= & gt;", they are not real Lambda expressions. Members of the expression body only indicate that the compiler generates a specific member behind the scenes.
The above is the detailed content of What Does `=>` Mean in C# Expression-Bodied Members?. For more information, please follow other related articles on the PHP Chinese website!