我有一個大型函式/子函式,在進入 ETL 設計模式之前,它會在早期進行大量驗證和錯誤檢查。所以我正在使用“C/C ”式的錯誤檢查,在你想要“提前失敗”的地方,即如果驗證失敗,我會盡快呼叫Return(與 相同Exit Sub)并且不執行進一步的代碼。
注意下面 VB.net 代碼中的重復代碼:
If fn Is Nothing Then
lblDataError.Text = "<b>Error!</b> Could not upload your file. <b>Reason:</b> Filename is blank, please press the <kbd>Browse</kbd> button first to select the file, then press <kbd>Upload</kbd>."
divFail.Visible = True
Return
ElseIf Path.GetExtension(fn).ToLower() <> ".csv" Then
lblDataError.Text = "<b>Error!</b> Could not upload your file. <b>Reason:</b> Filename extension must be <kbd>.csv</kbd>."
divFail.Visible = True
Return
Else
For Each badChar As Char In System.IO.Path.GetInvalidFileNameChars
If InStr(fn, badChar) > 0 Then
lblDataError.Text = "<b>Error!</b> Could not upload your file. <b>Reason:</b> Filename contains invalid character(s)."
divFail.Visible = True
Return
End If
Next
End If
是否可以創建一個輔助函式,使其導致呼叫函式回傳?如果這在 .NET 中是不可能的,是否有任何語言支持這一點?
Public Function Fail(customErrorMessage as String)
lblDataError.Text = "<b>Error!</b> " & customErrorMessage
divFail.Visible = True
Return Return 'This line should cause the calling function to return.
End Function
或者我應該只使用布林值并在所有驗證之后做一個 if 陳述句,因為這是不可能的?
uj5u.com熱心網友回復:
我建議你看看使用 try/catch 和例外。支持 C# 和我能想到的幾乎任何其他語言。
uj5u.com熱心網友回復:
以史蒂夫的想法為基礎……在每個驗證中呼叫失敗函式。你知道你會回來,所以是這樣的:
If fn Is Nothing Then
Call Fail("<b>Error!</b> Could not upload your file. <b>Reason:</b> Filename is blank, please press the <kbd>Browse</kbd> button first to select the file, then press <kbd>Upload</kbd>.")
Return
ElseIf ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397981.html
