尝试使用 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...
}
最佳答案
如果你想创建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
.
关于c# - 传递 bool 表达式作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474156/