2017-05-08 36 views
2

我正在將一些遺留代碼從VB6遷移到VB.NET,並且我遇到了一個煩人的問題。目前正在發生的是用戶提供了RadionButton控件來表示層次結構。當他們選擇一個值時,代碼會驗證它是否有效(不能讓C代表A的孩子,必須是B的孩子),如果不是,它會將RadioButton返回到原始設置。更改事件中的RadioButton checkstate

問題是,當執行此操作的函數返回到事件處理函數時,它將返回RadioButton狀態到單擊它時的狀態(用戶單擊C,代碼返回到B,函數退出時返回到C發射事件將再次變成B等,從而導致無限循環)。有沒有辦法改變哪個RadioButton is selected inside a function called by CheckedChanged`事件並讓它堅持?

我知道更好的設計是提前禁用無效的RadioButton控件,但這是它的設計方式,我的工作是讓它在有限的時間框架內工作,所以我現在被糟糕的設計困住了以後反對好設計。

代碼:

Private Sub optIndent_2_ClickEvent(sender As Object, e As EventArgs) Handles optIndent_2.CheckedChanged 
    optIndent_Click(2, sender.Checked) 
End Sub 

Private Sub optIndent_3_ClickEvent(sender As Object, e As EventArgs) Handles optIndent_3.CheckedChanged 
    optIndent_Click(3, sender.Checked) 
    Dim i As Integer = 1 
End Sub 

Private Sub optIndent_Click(ByRef Index As Short, ByRef value As Short) 
    If value = False Then 
     Exit Sub 
    End If 

    If Index = 2 Then 
     Exit Sub 
    End If 
    If Index = 3 Then 
     optIndent_2.Checked = True 
     Exit Sub 
    End If 
End Sub 

你會看到,當代碼退出optIndent_Click (3, sender.checked)值將會從虛假到真實的轉變,該進程將永遠重複。

回答

2

的問題是使用的ByRef

Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the argument in the calling code.

相反,你應該使用ByVal

Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.

更改參數value是一個ByVal參數將解決這個問題。這將阻止value保留其「價值」。

我明白,你堅持了糟糕的設計所以這可能不是適合這個項目範圍,但在某些時候你應該看看轉彎Option Strict On

Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.

這都強調ByVal value As Short作爲一個問題:

Option Strict On disallows implicit conversions from 'Boolean' to 'Short'.

修復將是; ByVal value As Boolean

有選項嚴格上也將突出sender.Checked爲一個錯誤:

Option Strict On disallows late binding

的解決將是投senderRadioButton這樣你就可以直接訪問它的屬性; DirectCast(sender, RadioButton).Checked

您的代碼看起來是這樣的:

Private Sub optIndent_2_ClickEvent(sender As Object, e As EventArgs) Handles optIndent_2.CheckedChanged 
    optIndent_Click(2, DirectCast(sender, RadioButton).Checked) 
End Sub 

Private Sub optIndent_3_ClickEvent(sender As Object, e As EventArgs) Handles optIndent_3.CheckedChanged 
    optIndent_Click(3, DirectCast(sender, RadioButton).Checked) 
End Sub 

Private Sub optIndent_Click(ByVal Index As Short, ByVal value As Boolean) 
    If value = False Then 
     Exit Sub 
    End If 

    If Index = 2 Then 
     Exit Sub 
    End If 

    If Index = 3 Then 
     optIndent_2.Checked = True 
     Exit Sub 
    End If 
End Sub