是否有可能将Func <bool>作为条件

Lou*_*ann 1 c# lambda loops

晚上好,

我想知道是否可以做类似的事情:

while(true)
{
   MyEnum currentValue = GetMyEnumValueFromDB();
   if(currentValue == MyEnum.BreakIfYouGetThis)
      break;
   else if(currentValue == MyEnum.AlsoBreakIfYouGetThis)
      break;
   else
      //Do some computing
}
Run Code Online (Sandbox Code Playgroud)

但是,除了要有一个while(true)循环外,我想将条件逻辑封装在Func中并像这样执行它:

while(new Func<bool>(/* what goes here? */))
{
   //Do some computing
}
Run Code Online (Sandbox Code Playgroud)

至少就我而言,它看起来要干净得多,但是我不确定该怎么做(Func / Action ..的新功能)。

EDIT希望这可以澄清:
也可以这样进行:

while(GetMyEnumValueFromDB() != MyEnum.BreakIfYouGetThis && 
      GetMyEnumValueFromDB() != MyEnum.AlsoBreakIfYouGetThis)
{
   //Do some computing
}
Run Code Online (Sandbox Code Playgroud)

但这就是对数据库的两次调用...

谢谢=)

Jon*_*eet 5

好吧,你可能有:

Func<bool> condition = ...;

while (condition())
{
}
Run Code Online (Sandbox Code Playgroud)

这就是您的想法吗?还不清楚...

编辑:在您给出的示例中,我将使用类似以下内容:

private static readonly MyEnum[] BreakEnumValues = { 
    MyEnum.BreakIfYouGetThis,
    MyEnum.AlsoBreakIfYouGetThis
};

...

while (!BreakEnumValues.Contains(GetMyEnumValueFromDB()))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

要么:

private static bool ShouldBreak(MyEnum enumFromDatabase)
{
    return enumFromDatabase == MyEnum.BreakIfYouGetThis ||
           enumFromDatabase == MyEnum.AlsoBreakIfYouGetThis;
}

...

while (!ShouldBreak(GetMyEnumValueFromDB))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:为了应对KeithS的回答,这是完全有效的:

while (new Func<bool>(() => {
    Console.WriteLine("Evaluating...");
    return true;
})()) {
    Console.WriteLine("In loop");
    count++;
    if (count == 5)
    {
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这太可怕了,但这是有效的。(通过显式调用Invoke,可以使它的恐惧程度降低一些,但仍然不是很好。)