3

这是 vb6 中的一个过程,它工作正常,就像包含的示例一样:

' Check_UnCheck

' 选中一些复选框的数组,取消选中另一个复选框的数组

' 用法示例:

CheckBox.Check_UnCheck Array(chkCheck3, chkCheck5), Array(chkCheck1, chkCheck4)


Public Sub Check_UnCheck(ByRef CheckArray As Variant, ByRef UnCheckArray As Variant)

    Dim i As Integer
    Dim conControl As Control

    For i = LBound(CheckArray) To UBound(CheckArray)
        Set conControl = CheckArray(i)
        conControl.Value = 1
    Next

    For i = LBound(UnCheckArray) To UBound(UnCheckArray)
        Set conControl = UnCheckArray(i)
        conControl.Value = 0
    Next

End Sub

上述过程在 vb.net 中的等效项是什么,MSDN 文档说:

  • 我们不能在一个过程中使用多个参数数组,它必须是过程定义中的最后一个参数。
4

2 回答 2

2

试试下面的代码。

查看评论以获取详细说明。

'DECLARE YOUR ARRAYS.
Dim array1 = New CheckBox() {CheckBox3, CheckBox5}
Dim array2 = New CheckBox() {CheckBox1, CheckBox4}

'CALL CHECK AND UNCHECK FUNCTION.
Check_UnCheck(array1, array2)


'YOUR FUNCTION DEFINITION.
Public Sub Check_UnCheck(ByRef CheckArray As CheckBox(), ByRef UnCheckArray As CheckBox())

    'LOOP FIRST ARRAY AND CHECK THEM.
    For index = 0 To CheckArray.GetUpperBound(0)
        CheckArray(index).Checked = True
    Next

    'LOOP SECOND ARRAY AND UNCHECK THEM.
    For index = 0 To UnCheckArray.GetUpperBound(0)
        UnCheckArray(index).Checked = False
    Next

End Sub
于 2017-09-26T22:21:58.373 回答
1

首先,您将“参数数组”与控件数组混淆,它们不是一回事。参数数组是当一个方法采用可变数量的参数(所有相同类型)时,编译器然后将这些参数捆绑到一个数组中并将其传递给该方法。为了实现这一点,该方法必须使用关键字ParamArray

VB.net 没有 vb6 那样的 conrtol 数组,但这不是您的示例所使用的。你的例子是使用一个简单的控件数组。顺便说一句,您的示例使用的是 ByRef,这是 VB6 中的默认设置,但在这种情况下,对于 VB6 和 VB.net 来说都是不必要的。鉴于它在 VB.net 中的使用不再是默认设置,因此不必要地使用它会产生误导。

您传入两个数组,第二个可能是 ParamArray 但这样做没有什么意义。

让您的代码工作的基本和最小更改很简单,将“Variant”更改为“CheckBox()”。但这不是我推荐的。还有一些其他的小改动使它更灵活、更易读。

Public Sub Check_UnCheck(CheckArray As IEnumerable(Of CheckBox), 
                         UnCheckArray As IEnumerable(Of CheckBox)) 
    ' Here I have replaced the Variant, which is not supported in
    ' .net, with the generic IEnumerable of checkbox.  I used an
    ' Ienumerable, instead of an array because it will allow making 
    ' just a minor change to the call site.

    ' here I have eliminated the index variable, and moved the  
    ' declaration of the conControl variable into the for each.  
    ' Option Infer On statically types the variable as a checkbox
    For Each conControl In CheckArray
        ' Checkbox controls do not have a value property.
        ' 1 is not true, true is true.
        conControl.Checked = True
    Next

    For Each conControl in UnCheckArray
        conControl.Checked = False
    Next

End Sub

然后会这样调用: Check_UnCheck({chkCheck3, chkCheck}, {chkCheck1, chkCheck4})

于 2017-09-29T23:35:46.287 回答