От: | Sinix | ||
Дата: | 21.11.14 07:39 | ||
Оценка: | 22 (3) |
Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.
Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:
public Point Move(int dx, int dy) => new Point(x + dx, y + dy); public static Complex operator +(Complex a, Complex b) => a.Add(b); public static implicit operator string(Person p) => "\{p.First} \{p.Last}";
The effect is exactly the same as if the methods had had a block body with a single return statement.
For void returning methods – and Task returning async methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression (just as is the rule for lambdas):
public void Print() => Console.WriteLine(First + " " + Last);
Properties and indexers can have getters and settersgetter-only properties and indexers can have an expression body:
public string Name => First + " " + Last; public Customer this[long id] => store.LookupCustomer(id);