繁体   English   中英

void方法中的return语句

[英]return statement in void methods

所以,我最近寻找在C#中使用一个小型图书馆的FTP ...我通过了这个问题这一类....

我想知道所有其void方法中的return语句的含义...

例如,这是其删除方法:

     /* Delete File */
public void delete(string deleteFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Resource Cleanup */
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

我的问题是:

return; 任何原因或结果?

通过查看页面,每种方法都以模式结尾

catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return /* Whatever the "default" return value would be on a error */;

作为void方法中的最后一条语句return的结果不会对程序产生任何影响,我唯一的猜测是这是本文发布者喜欢遵循的模式。 他用他的其他方法返回了一个字符串。

catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return "";

因此他可能只想在返回void的方法上保持相同的模式。

没有。

这可以用于方法的早期返回,但是这里不是这种情况return; 方法的最后是完全多余的。

只要您禁用了优化 ,生成的IL代码就会有明显的不同。 没有return语句的void方法将仅包含ret指令,同时添加return; 最后将添加一个分支指令-跳转到ret指令。

无需编写无意义的解释,答案很简单:没有任何意义

它没有任何作用,但我也看到过。 我推测(!),有些人希望以return结束其方法,以便在块的末尾比在右括号中具有更大的可视指示。 如果您稍后再更改返回类型(从void更改为其他内容),也可能会节省您一秒钟的时间。

您的代码存在一些问题

  1. 如果抛出异常,则不会关闭 ftpReques t(资源泄漏)
  2. 您是否真的要重新创建类字段( ftpRequest )?
  3. 捕捉Exception气味
  4. 最后的return是无用的(您的问题)

修改后的代码可能是这样的:

public void delete(string deleteFile) {
  try {
    // using over IDisposable is 
    using (var ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile)) {
      ftpRequest.Credentials = new NetworkCredential(user, pass);
      // When in doubt, use these options 
      ftpRequest.UseBinary = true;
      ftpRequest.UsePassive = true;
      ftpRequest.KeepAlive = true;
      // Specify the Type of FTP Request 
      ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
      // Establish Return Communication with the FTP Server 
      ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
    }
  }
  catch (WebException ex) {
    Console.WriteLine(ex.ToString());
  }
}

void方法末尾的return语句不会产生任何其他影响。 可以在不更改方法语义的情况下将其删除。

可以使用该return来简化对函数返回位置的文本搜索,但对编译器无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM