为了清晰起见,从功能中返回enum而不是bool?

Moe*_*sko 7 c# coding-style

这类似于:

.NET:bool vs enum作为方法参数

但是担心在某些情况下从函数返回bool.

例如返回bool的函数:

    public bool Poll()
    {
        bool isFinished = false;

        // do something, then determine if finished or not.

        return isFinished;
    }
Run Code Online (Sandbox Code Playgroud)

像这样使用:

        while (!Poll())
        {
            // do stuff during wait.
        }
Run Code Online (Sandbox Code Playgroud)

从调用上下文来看,从Poll()返回的bool意味着什么并不明显.如果"轮询"功能被重命名为"IsFinished()",在某些方面可能更清楚,但该方法做了一些工作,并且(IMO)不会真正反映该功能实际上做了什么.像"IsFinished"这样的名字似乎也更适合于属性.另一种选择可能是将其重命名为:"PollAndReturnIsFinished",但这也感觉不对.

所以一个选项可能是返回枚举.例如:

    public enum Status
    {
        Running,
        Finished
    }  

    public Status Poll()
    {
        Status status = Status.Running;

        // do something, then determine if finished or not.

        return status;
    }
Run Code Online (Sandbox Code Playgroud)

这样称呼:

        while (Poll() == Status.Running)
        {
            // do stuff during wait.
        }
Run Code Online (Sandbox Code Playgroud)

但这感觉有点矫枉过正.有任何想法吗 ?

Rob*_*son 3

方法应该像动词一样读,而该方法的结果bool Poll()具有误导性,这可能就是使用起来感觉尴尬的原因。

// you wrote.
while( !Poll() )
{
    // still waiting .. do something.
}
Run Code Online (Sandbox Code Playgroud)

当我第一次阅读你的代码时,我认为它说的是“当(系统)不轮询时,做点什么? ”

但它确实说......民意调查,如果没有完成民意调查,在我们等待时做点什么。

您的枚举版本似乎改变了调用的语义,但变得更好,这就是人们喜欢它的原因。当 Poll() 仍在运行时,在等待时做一些事情。

最易读的代码获胜。