vb.net
  • if-statement
  • code-formatting
  • 2017-03-07 57 views 1 likes 
    1

    我對VB.NET並不熟悉,爲了試着理解遺留代碼(這是很快格式化的),我保持更好的狀態,我將它送入壓縮機here這是VB.NET代碼的正確格式(對於grokkability)嗎?

    但是,這是一個什麼樣出來它的一部分:

    currentYear = Year(Now) 
    SQLString = "Select NewBiz from MasterUnitsprojSales where CYear = " & currentYear & " and Unit = '" & Unit & "'" 
    adoRS = New ADODB.Recordset 
    adoRS.Open(SQLString, adoCon) 
    IsNewBusiness = TRUE 'default (if record not found) 
    Category = "New Business" 
    If Not adoRS.EOF Then 
        IsNewBusiness = adoRS.Fields.Item(0).Value <> 0 
        if Not IsNewBusiness 
        Category = "Existing Business" 
    End If 
    Response.Write("<!-- IsNewBusiness after NOT adoRS.EOF check = " & CStr(IsNewBusiness) & " -->") 
    End If 
    adoRS.Close() 
    
    If Request.Form.Item("Action") = "Save" Then 
    Response.Write("<!-- Made it into the Action =Save block -->") 
    Unit = Request.Form.Item("Unit") 
    . . . 
    

    這是正確的?在我看來,它應該是更多這樣的:

    currentYear = Year(Now) 
    SQLString = "Select NewBiz from MasterUnitsprojSales where CYear = " & currentYear & " and Unit = '" & Unit & "'" 
    adoRS = New ADODB.Recordset 
    adoRS.Open(SQLString, adoCon) 
    IsNewBusiness = TRUE 'default (if record not found) 
    Category = "New Business" 
    If Not adoRS.EOF Then 
        IsNewBusiness = adoRS.Fields.Item(0).Value <> 0 
        if Not IsNewBusiness 
          Category = "Existing Business" 
        End If 
        Response.Write("<!-- IsNewBusiness after NOT adoRS.EOF check = " & CStr(IsNewBusiness) & " -->") 
    End If 
    adoRS.Close() 
    
    If Request.Form.Item("Action") = "Save" Then 
        Response.Write("<!-- Made it into the Action =Save block -->") 
        Unit = Request.Form.Item("Unit") 
        . . . 
    

    我知道這只是格式化,它不會導致代碼工作有什麼不同,但它會幫助我很多有它正確格式化(特別是與「如果」和「endif」等排隊)。

    任何時候如果有「如果」,必須有一個對應的「結束」如果?

    假設是如此,這indenterized代碼更加混亂:

    If Not adoRS.EOF Then 
    CustomerChk = adoRS.Fields.Item(0).Value 
    adoRS.Close() 
    If CustomerChk <> CustNo Then 
    

    ...難道不應該是:

    If Not adoRS.EOF Then 
        CustomerChk = adoRS.Fields.Item(0).Value 
        adoRS.Close() 
        If CustomerChk <> CustNo Then 
    

    ?否則,如果塊沒有任何明確的說法結束,它會看起來像第一塊。

    +2

    嘗試菜單編輯/高級/格式化文檔 –

    +1

    代碼中出現了一個錯誤,它會讓您的縮進機器感到困惑。 「如果不是新商業」應該是'如果不是新商業那麼'(注意最後的'那麼')。 – Blackwood

    +1

    你不應該像這樣創建sql字符串。始終使用參數。它避免了sql注入和格式錯誤。 – LarsTech

    回答

    1

    關於你的VB.NET問題...

    1)這是[代碼縮進更新]正確嗎?

    它對我來說很合適。我可能會在if代碼塊之前和之後插入空白行,但這只是我個人的偏好,而不是VB.NET的要求。

    2)任何時候有一個「如果」必須有一個對應的「結束」如果?

    通常這是約定,但這不是VB.NET的要求。 VB.NET允許單行「If」語句,如在MSDN page上引用的以下行。

    ' If A > 10, execute the three colon-separated statements in the order 
    ' that they appear 
    If A > 10 Then A = A + 1 : B = B + A : C = C + B 
    
    相關問題