为什么我们不需要在`using`范围之外返回一个值?

3 c#

考虑以下代码:

public int DownloadSoundFile()
{
   using (var x= new X())
   {
       return x.Value;
   }
}
Run Code Online (Sandbox Code Playgroud)

而这段代码:

public int DownloadSoundFile()
{
    if (x!=null)
    {
       return x.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个代码没有给我们任何编译时错误,但在第二个代码中我们得到这个错误:

并非所有代码路径都返回一个值

这意味着我们应该返回if范围之外的值.

为什么我们必须返回if范围之外的值,但不需要返回using范围之外的值?

Dar*_*rov 20

为什么我们应该从if范围返回值,但是不需要使用Scope的返回值?

因为if范围可能不会执行(如果条件不满足),而using范围的主体保证始终执行(它将返回结果或抛出编译器可接受的异常).对于if范围,如果不满足条件并且编译器拒绝该方法,则您的方法是未定义的.

因此,如果您写的条件不满足,您应该决定返回什么值:

public int DownloadSoundFile()
{
    if (x != null)
    {
       return x.Value;
    }

    // at this stage you should return some default value
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 在处理`IDisposable`实例时,你应该使用`using`.它将确保始终调用Dispose方法. (3认同)

Hen*_*man 7

所以我们应该从if范围中返回值.

不,你应该从一个值返回一个值int method().它与if()vs 无关using().

public int DownloadSoundFile()
{
    if (x!=null)
    {
        return x.Value;
    }
    // and now?? no return value for the method
    // this is a 'code path that does not return a value'
}
Run Code Online (Sandbox Code Playgroud)