如何编写带有“=>”的多行方法?
public int SimpleAddition(int firstInt, int secondInt) => firstInt + secondInt;
如果我没记错的话,上面的方法相当于:
public int SimpleAddition(int firstInt, int secondInt){
return firstInt + secondInt;
}
如果逻辑跨越多行,我将如何使用“=>”编写此方法?
public int SimpleAddition(int firstInt, int secondInt){
//do something else here//
return firstInt + secondInt;
}
如果逻辑跨越多行,我将如何使用“=>”编写此方法?
你不会。以下:
public int SimpleAddition(int firstInt, int secondInt) => firstInt + secondInt;
是 表达式主体方法 和表达式主体成员,如文档所述只能由单个表达式组成:
表达式主体定义让您能够以简洁、可读的形式提供成员的实现。 只要任何受支持的成员(例如方法或属性)的逻辑由单个表达式组成,您就可以使用表达式主体定义。
请注意,例如多个链式方法调用(如 Fluent APIs/LINQ)仍然形成单个表达式。例如:
public int SimpleAddition(int firstInt, int secondInt)
=> new[] { firstInt, secondInt } // just for example
.Where(_ => true)
.Sum();
因此,如果您可以以可以链接(或形成单个表达式)的方式重写附加代码,那么您将能够将方法重写为表达式主体(但这并不意味着您应该这样做)。