1

我有一个要编译成程序集的文本文件,使用 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被正确修改。

4

1 回答 1

2

但是评论总是“Foo”(消息框显示“不允许”),所以看起来 ByRef 修饰符不起作用

是的,但是您使用不正确,期望不正确:)

创建参数数组时,您将 的值复制comment数组中。方法完成后,您将无法再访问该数组,因此您看不到它已更改。数组中的更改不会影响 的值comment,但会展示其ByRef性质。所以你想要的是:

Dim arguments As Object() = New Object() { 1234, comment }
method.Invoke(_scriptClass, arguments)
Debug.WriteLine(arguments(1))
于 2014-02-11T12:04:00.780 回答