![](/img/trans.png)
[英]Can you use the “return” statement in C# methods declared as void?
[英]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更改為其他內容),也可能會節省您一秒鍾的時間。
您的代碼存在一些問題 :
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
來簡化對函數返回位置的文本搜索,但對編譯器無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.