![](/img/trans.png)
[英]Method.Invoke() behaving strangely C# .NET BackgroundWorker
[英]How can I get ByRef Arguments to work in a dynamically created assembly with Method.Invoke
我有一個文本文件,正在使用VBCodeProvider類編譯為程序集
該文件如下所示:
Imports System
Imports System.Data
Imports System.Windows.Forms
Class Script
Public Sub AfterClockIn(ByVal clockNo As Integer, ByRef comment As String)
If clockNo = 1234 Then
comment = "Not allowed"
MessageBox.Show(comment)
End If
End Sub
End Class
這是編譯代碼:
Private _scriptClass As Object
Private _scriptClassType As Type
Dim codeProvider As New Microsoft.VisualBasic.VBCodeProvider()
Dim optParams As New CompilerParameters
optParams.CompilerOptions = "/t:library"
optParams.GenerateInMemory = True
Dim results As CompilerResults = codeProvider.CompileAssemblyFromSource(optParams, code.ToString)
Dim assy As System.Reflection.Assembly = results.CompiledAssembly
_scriptClass = assy.CreateInstance("Script")
_scriptClassType = _scriptClass.GetType
我想做的是在方法內部修改注釋字符串的值,以便在我從代碼中調用它之后可以檢查該值:
Dim comment As String = "Foo"
Dim method As MethodInfo = _scriptClassType.GetMethod("AfterClockIn")
method.Invoke(_scriptClass, New Object() {1234, comment})
Debug.WriteLine(comment)
但是注釋始終為"Foo"
(消息框顯示為"Not Allowed"
),因此ByRef修飾符似乎無法正常工作
如果我在代碼中使用相同的方法,則comment
被正確修改。
但是注釋始終是“ Foo”(消息框顯示“不允許”),因此ByRef修飾符似乎不起作用
是的,但是您使用不正確,期望值不正確:)
創建自變量數組時, 將 comment
的值復制到該數組中。 方法完成后,您將無法再訪問數組,因此看不到它已更改。 數組中的更改不會影響comment
的值,但會顯示ByRef
性質。 所以您想要的是:
Dim arguments As Object() = New Object() { 1234, comment }
method.Invoke(_scriptClass, arguments)
Debug.WriteLine(arguments(1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.