2017-05-08 32 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