猿问

使用Lambda属性-编译器

如果有人可以帮助我解决问题,我只是不了解某些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; } 

    }

    */

}


蝴蝶刀刀
浏览 194回答 2
2回答

噜噜哒

简短答案关键在于,表达强健的成员需要一个表达而不是一个陈述。member => expression;因此,问题在于您的if陈述。尝试另一种方法,例如三元表达式。// use a ternarypublic int MyProperty => Check ? 1 : 0;// or a Lazy, if you want to emulate Scalapublic int MyOtherProperty =>&nbsp;&nbsp; &nbsp; new Lazy<int>(() => { if (Check) return 1; else return 0; }).Value;完整的例子这里是小提琴。using System;public interface In1{&nbsp; &nbsp; int MyProperty { get; }&nbsp; &nbsp; bool Check { get; }}class TestProp : In1{&nbsp; &nbsp; // use a ternary&nbsp; &nbsp; public int MyProperty => Check ? 1 : 0;&nbsp; &nbsp; // or a Lazy, if you want to emulate Scala&nbsp; &nbsp; public int MyOtherProperty =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; new Lazy<int>(() => { if (Check) return 1; else return 0; }).Value;&nbsp; &nbsp; public bool Check => true;}

蝴蝶不菲

称为表达式主体成员(使用=>)。它仅接受一行。您if&nbsp;else是无效的,因为它是多行。试试吧public&nbsp;int&nbsp;MyProperty&nbsp;=>&nbsp;Check&nbsp;?&nbsp;1&nbsp;:&nbsp;0;这使用三元运算符使它成为单个语句。之所以get有效,是因为它用大括号括起来,不再需要是一行。如果这样做,get => if (Check) return 1; else return 0;您将得到相同的错误。
随时随地看视频慕课网APP
我要回答