如何定义布尔表达式并仅在使用时对其进行评估?
How to define a boolean expression and evaluate it only when used?
我们直接举个例子:
public bool MeetsAllConditions()
{
bool check1, check2, check3;
// Some code to define result of check1
if (something...)
{
if (something...)
{
check1 = true;
}
}
// many more code to define check2 and check3
....
if (check1 && check2 && check3)
{
return true;
}
return false;
}
现在,定义每个 check
的代码非常 昂贵 。因此,我想这样做,以便定义每个检查结果的代码被评估 only in the final if
语句。这样,如果 any 的检查 fails.
,我可以利用惰性求值来节省资源
如果不为 C# 中的每个 check
定义一个单独的方法,我将如何处理这个 ?
这取决于你所说的 "separate method" 是什么意思。如果您愿意在代码中内联创建委托,您可以这样做:
Func<bool> check1 = () =>
{
if(something...)
{
if(something...)
{
return true;
}
}
}
...
return check1() && check2() && check3();
另一种选择是简单地短路并 return 任何时候当你注意到应该导致你 return 错误的东西时尽早。
if(!something...)
{
return false;
}
if(!something...)
{
return false;
}
... // same pattern for check2 and check3
return true;
为什么不使用 Lazy<T>
?
来自MSDN
Use lazy initialization to defer the creation of a large or
resource-intensive object, or the execution of a resource-intensive
task, particularly when such creation or execution might not occur
during the lifetime of the program.
既然你提到了昂贵的过程,为什么不把昂贵的过程封装在一个类型中呢?
我们直接举个例子:
public bool MeetsAllConditions()
{
bool check1, check2, check3;
// Some code to define result of check1
if (something...)
{
if (something...)
{
check1 = true;
}
}
// many more code to define check2 and check3
....
if (check1 && check2 && check3)
{
return true;
}
return false;
}
现在,定义每个 check
的代码非常 昂贵 。因此,我想这样做,以便定义每个检查结果的代码被评估 only in the final if
语句。这样,如果 any 的检查 fails.
如果不为 C# 中的每个 check
定义一个单独的方法,我将如何处理这个 ?
这取决于你所说的 "separate method" 是什么意思。如果您愿意在代码中内联创建委托,您可以这样做:
Func<bool> check1 = () =>
{
if(something...)
{
if(something...)
{
return true;
}
}
}
...
return check1() && check2() && check3();
另一种选择是简单地短路并 return 任何时候当你注意到应该导致你 return 错误的东西时尽早。
if(!something...)
{
return false;
}
if(!something...)
{
return false;
}
... // same pattern for check2 and check3
return true;
为什么不使用 Lazy<T>
?
来自MSDN
Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.
既然你提到了昂贵的过程,为什么不把昂贵的过程封装在一个类型中呢?