void方法中的return语句
本文关键字:return 语句 方法 void | 更新日期: 2023-09-27 18:01:08
所以,我最近在C#中搜索使用FTP的小库。。。我把这个问题交给了全班同学。。。。
我想知道return
语句在所有void方法中的意义。。。
以下是他们的删除方法:
/* 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更改为其他类型(,也可以节省一秒钟的时间。
您的代码存在一些问题:
- 如果抛出异常,
ftpReques
t将不会关闭(资源泄漏( - 是否确实要重新创建类字段(
ftpRequest
( - 捕捉
Exception
气味 - 最后一个
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
来简化对函数返回位置的文本搜索,但它对编译器没有影响。