为了账号安全,请及时绑定邮箱和手机立即绑定

使用Lambda属性-编译器

使用Lambda属性-编译器

C#
蝴蝶刀刀 2021-04-06 21:42:28
如果有人可以帮助我解决问题,我只是不了解某些C#接口方法等。我注意到,在某些情况下,使用=>表达式时,我实际上无法访问所在的类。但是,一个简单的长期修订(下面有评论)可以轻松地对其进行修复。我不确定我是否看到任何区别...我尝试过将行包装在{ }标记中,等等。真的可以使用一些智慧-谢谢!public interface In1{         int MyProperty { get; }         bool Check { get; }}class TestProp : In1{    public int MyProperty => if (Check) return 1; else return 0; //ERROR THE NAME CHECK DOES NOT EXIST IN THE CURRENT CONTEXT    public bool Check => true;    /* will compile    public int MyProperty    {        get { if (Check) return 1; else return 0; }     }    */}
查看完整描述

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;

}


查看完整回答
反对 回复 2021-04-17
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

称为表达式主体成员(使用=>)。它仅接受一行。您if else是无效的,因为它是多行。试试吧

public int MyProperty => Check ? 1 : 0;

这使用三元运算符使它成为单个语句。

之所以get有效,是因为它用大括号括起来,不再需要是一行。如果这样做,get => if (Check) return 1; else return 0;您将得到相同的错误。


查看完整回答
反对 回复 2021-04-17
  • 2 回答
  • 0 关注
  • 150 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信