阵列如在过程vb6的VS vb.net
问题描述:
这里的参数是在VB6的程序和类似的示例中,工作正常包括:阵列如在过程vb6的VS vb.net
“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文档说:
- 我们不能在过程使用超过一个参数数组,而且它必须是过程定义中的最后一个参数。
答
请尝试以下代码。
请查看评论以了解详细说明。
'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
答
首先,您将“参数数组”与一组控件混淆在一起,它们不是同一件事。参数数组是当一个方法接受可变数量的参数(所有相同类型)时,编译器将这些参数绑定到一个数组中并将其传递给该方法。为了发生这种情况,该方法必须使用关键字ParamArray。
VB.net在vb6没有的情况下没有conrtol数组,但这不是你正在使用的例子。你的例子是使用一个简单的控件数组。另外,您的示例使用的是ByRef,它是VB6中的默认值,但在这种情况下,对于VB6和VB.net都是不必要的。鉴于它在VB.net中的使用已不再是默认设置,因此不必要地使用它会产生误导。
您正在传递两个数组,第二个数组可能是ParamArray,但这样做没有多大意义。
让代码工作的基本和最小变化很简单,将“变体”更改为“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})
你可以** **有一个以上的参数数组的方法。你提到的限制是“ParamArray”不是一回事。 – Plutonix