Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet63/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   59   60   61   62   63   64   65   66   ...   78
Bog'liq
C sharp

 Expression Body Members
Lambda expressions provide a shorthand alternative way to define class 
members in cases when the member consists of only a single expression. 
This is called an expression body definition. Consider the following class.
class Person
{
public string name { get; } = "John";
public void PrintName() {
System.Console.WriteLine(name);
}
}
These member bodies can be rewritten as expression bodies instead, 
which are easier to read.
class Person
{
public string name => "John";
public void PrintName() =>
System.Console.WriteLine(name);
}
Chapter 26 Delegates


149
Support for implementing member bodies as lambda expressions was 
added in C# 6.0 for methods and get properties. C# 7.0 extended this list of 
allowed members to also include constructors, destructors, set properties, 
and indexers. To illustrate, here is an example using expression bodies for 
a constructor and a property that has both set and get accessors.
class Person
{
private string firstName;
public string name
{
get => firstName;
set => firstName = value;
}
public Person(string name) => this.name = name;
}
 Multicast Delegates
It is possible for a delegate object to refer to more than one method. Such 
an object is known as a multicast delegate, and the methods it refers to 
are contained in a so-called invocation list. To add another method to 
the delegate’s invocation list, either the addition operator or the addition 
assignment operator can be used.
static void Hi() { System.Console.Write("Hi"); }
static void Bye() { System.Console.Write("Bye"); }
// ...
MyDelegate del = Hi;
del = del + Hi;
del += Bye;
Chapter 26 Delegates


150
Similarly, to remove a method from the invocation list, the subtraction 
or subtraction assignment operators are used.
del -= Hi;
When calling a multicast delegate object, all methods in its invocation 
list will be invoked with the same arguments in the order that they were 
added to the list.
del(); // "HiBye"
If the delegate returns a value, only the value of the last invoked 
method will be returned. Likewise, if the delegate has an out parameter, its 
final value will be the value assigned by the last method.

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   59   60   61   62   63   64   65   66   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling