我试图使用lambda
/ LINQ
Expression
或Func<bool>
来简单地替换bool
返回类型来尝试实现更优雅的通用解决方案
说表达式是:
public bool someBoolRetMethod(someType parA, someOtherType parB) {
if(parA==null)
return new ExpM("relevant msg").Rtrn;
}
所以如果parA
是null
,ExpM()
是一个处理错误的类
我想要做的是将条件作为参数传递:
public class ExpBoolCond:ExpM {
public bool Rtrn{get;set;}
public ExpBoolCond(theBool, themsg) {
variable to hold theBool;
if(theBool) new specialMbxWindow(themsg)
then set Rtrn..
}
}
所以这样我可以使用:
var condNullParA = new ExpBoolCond(parA==null, "passed ParA is Null,\r\nAborting method <sub>(methodName and line# is handled inside ExpM base class)</sub> !")
if(condNullParA.Rtrn) ....
实施它的正确方法是什么?
更新:
public class ExcBCondM:ExcpM
{
public bool Rtrn { get { return this._Rtrn(); } }
Func<bool> _Rtrn { get; set; }
public ExcBCondM(Func<bool> cond, string bsMsg)
: base(bsMsg,false)
{
this._Rtrn = cond;
//if (this._Rtrn) this.show();
}
public bool activateNon() { this.show(); return false; }
}
用法:
public bool someBoolRetMethod(some_passed_Type parA)
{
var someCondExpM = new ExpBoolCond(() => parA==null, "relevant Message");
if(someCondExpM.Rtrn)
return someCondExpM.activateNon(); //if() now Calls Func<bool> _Rtrn when called rather where stated.
return true;//if ok...
}
答案 0 :(得分:2)
如果要将Func<bool>
创建为lambda表达式,语法如下:
var condNullParA = new ExpBoolCond(() => parA==null, "passed ParA is Null,\r\nAborting method <sub>(methodName and line# is handled inside ExpM base class)</sub> !")
// ^^^^^
() =>
部分告诉C#编译器,后面的表达式应该成为不带参数的lambda的主体,并返回=>
符号右侧表达式的任何类型,即bool
。