![](/img/trans.png)
[英]How can I have a sub that accepts a variable as byref without declaring what type of variable it is?
[英]How value from different class/form can be changed without ByRef
讓我們假設以下示例:
當我從Form1調用Form2並傳遞Form1值的_name時。 當我顯示Form1的_name = Alex時? 我沒有在Form2中更改pname,並且構造函數不包含ByRef。
示例代碼:
Public Form1
Public _name as String
Sub New
_name = "John"
Dim bla as New Form2(_name)
'now _name=Alex !!
End Sub
End Class
Public Form2
Property _name2 as String
Sub New(pname as String) 'no ByVal !!
_name2 = pname 'even if would be ByVal no pname changed !
_name2 = "Alex"
End Sub
End Class
為什么會這樣呢?
在變量_name中使用共享:
Class Form1 Public Shared _name As String Public Sub New() _name = "John" End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Message "John" MessageBox.Show(_name) Dim bla As New Form2() bla.Show() ' Message "Alex" MessageBox.Show(_name) End Sub End Class Public Class Form2 Property _name2 As String Sub New() _name2 = "Alex" Form1._name = _name2 End Sub Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' message Alex MessageBox.Show(_name2) ' message Alex MessageBox.Show(Form1._name) End Sub End Class
要么
要更改參數的基礎值, 必須使用ByRef modifer
:
指定以這樣一種方式傳遞參數:被調用的過程可以更改調用代碼中作為該參數基礎的變量的值。
這與ByVal略有不同:
指定以這樣一種方式傳遞參數:被調用的過程或屬性不能更改調用代碼中作為該參數基礎的變量的值。
通過在VB.NET
未指定modifier
,默認情況下編譯器將使用ByVal
。
在這里最好注意一下,盡管默認情況下
VB.NET
使用ByVal
(如果未指定),而VBA
則不使用,而默認情況下使用ByRef
。 當您將代碼從一個移植到另一個時,請當心。
此外,您要更改name2
,而如果您想更改基礎值, 則應該更改pname
。
根據您的示例查看以下代碼:
Public Class Form1
Private _name As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
_name = "John"
Dim bla As New Form2(_name)
bla.Show()
Debug.WriteLine(_name)
End Sub
End Class
Public Class Form2
Private Property _name2 As String
Public Sub New(ByRef pname As String)
InitializeComponent()
_name2 = pname
pname = "Alex"
End Sub
End Class
在將值傳遞給Form2
之前,名稱為“ John”:
此時,我將pname
的值更改為“ Alex”:
請注意,盡管我已將
pname
的值更改為“ Alex”,但_name2
仍設置為“ John”。
請注意,由於對pname
所做的更改, _name
的值如何更改為“ Alex”:
我不確定您要在這里實現什么,但是希望該示例可以使您更好地理解。 另一種方法是使用共享變量,如其他答案中所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.