[英]Declare static class or struct method using expression body in C#
我一直在使用不可變的readonly
字段以及public
Expression<Func<>>
getter,如下所示。
public class Person
{
public static Person Named(string surname, string given) { return new Person(surname, given); } // ugly!
protected Person(string surname, string given) { _surname = surname; _given = given; }
private readonly string _surname;
private readonly string _given;
public string Name => _given + _surname; // cool!
}
我真的很想能夠使用上面的靜態方法做到這一點。
我嘗試了不同的語法,但是沒有用,即:
public static Person Named => x,y => new Person(x,y);
public static Person Named = (x,y) => new Person(x,y);
public static Person Named => ((x,y) => new Person(x,y));
正確的方法如下
public static Person Named(string surname, string given) => new Person(surname, given);
值得一提的是,實例和靜態屬性/方法的語法沒有區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.