2017-09-26 72 views
3

這裏的參數是在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文檔說:

  • 我們不能在過程使用超過一個參數數組,而且它必須是過程定義中的最後一個參數。
+3

你可以** **有一個以上的參數數組的方法。你提到的限制是「ParamArray」不是一回事。 – Plutonix

回答

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 
+0

此方法不需要使用ByRef參數 – jmoreno

+0

@jmoreno它可能更清楚(特別是對於新語言的人),即使在技術上冗餘的情況下,也可以明確地調用ByRef。 – DaveInCaz

+0

@DaveInCaz:這不是多餘的,它是一個謊言。 ByRef說,調用方法中用作參數的變量可能會改變。這沒有發生.. – jmoreno

1

首先,您將「參數數組」與一組控件混淆在一起,它們不是同一件事。參數數組是當一個方法接受可變數量的參數(所有相同類型)時,編譯器將這些參數綁定到一個數組中並將其傳遞給該方法。爲了發生這種情況,該方法必須使用關鍵字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})