简体   繁体   English

如何使用Method.Invoke使ByRef参数在动态创建的程序集中工作

[英]How can I get ByRef Arguments to work in a dynamically created assembly with Method.Invoke

I have a text file that I am compiling into an assembly use the VBCodeProvider class 我有一个文本文件,正在使用VBCodeProvider类编译为程序集

The file looks like this: 该文件如下所示:

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

Here is the compile code: 这是编译代码:

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

What I want to do is to modify the value of the comment String inside the method, so that after I call it from code I can inspect the value: 我想做的是在方法内部修改注释字符串的值,以便在我从代码中调用它之后可以检查该值:

Dim comment As String = "Foo"
Dim method As MethodInfo = _scriptClassType.GetMethod("AfterClockIn")
method.Invoke(_scriptClass, New Object() {1234, comment})
Debug.WriteLine(comment)

However comment is always "Foo" (message box shows "Not Allowed" ), so it appears that the ByRef modifier is not working 但是注释始终为"Foo" (消息框显示为"Not Allowed" ),因此ByRef修饰符似乎无法正常工作

If I use the same method in my code comment is correctly modified. 如果我在代码中使用相同的方法,则comment被正确修改。

However comment is always "Foo" (message box shows "Not Allowed"), so it appears that the ByRef modifier is not working 但是注释始终是“ Foo”(消息框显示“不允许”),因此ByRef修饰符似乎不起作用

It is, but you're using it incorrectly, with incorrect expectations :) 是的,但是您使用不正确,期望值不正确:)

When you create the argument array, you're copying the value of comment into the array. 创建自变量数组时, comment 的值复制到该数组中。 After the method has completed, you no longer have access to the array, so you can't see that it's changed. 方法完成后,您将无法再访问数组,因此看不到它已更改。 That change in the array won't affect the value of comment , but demonstrates the ByRef nature. 数组中的更改不会影响comment的值,但会显示ByRef性质。 So what you want is: 所以您想要的是:

Dim arguments As Object() = New Object() { 1234, comment }
method.Invoke(_scriptClass, arguments)
Debug.WriteLine(arguments(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM