2 回答
TA贡献1784条经验 获得超7个赞
简短答案
关键在于,表达强健的成员需要一个表达而不是一个陈述。
member => expression;
因此,问题在于您的if陈述。尝试另一种方法,例如三元表达式。
// use a ternary
public int MyProperty => Check ? 1 : 0;
// or a Lazy, if you want to emulate Scala
public int MyOtherProperty =>
new Lazy<int>(() => { if (Check) return 1; else return 0; }).Value;
完整的例子
这里是小提琴。
using System;
public interface In1
{
int MyProperty { get; }
bool Check { get; }
}
class TestProp : In1
{
// use a ternary
public int MyProperty => Check ? 1 : 0;
// or a Lazy, if you want to emulate Scala
public int MyOtherProperty =>
new Lazy<int>(() => { if (Check) return 1; else return 0; }).Value;
public bool Check => true;
}
TA贡献1810条经验 获得超4个赞
称为表达式主体成员(使用=>
)。它仅接受一行。您if
else
是无效的,因为它是多行。试试吧
public int MyProperty => Check ? 1 : 0;
这使用三元运算符使它成为单个语句。
之所以get
有效,是因为它用大括号括起来,不再需要是一行。如果这样做,get => if (Check) return 1; else return 0;
您将得到相同的错误。
- 2 回答
- 0 关注
- 193 浏览
添加回答
举报