执行运行时代码参数

时间:2011-12-09 05:02:50

标签: vb.net

以下是在运行时执行代码的一些代码:

    Dim SourceCode As String = txtCode.Text

    Dim Dlls() As String = {"System.dll", "System.Core.dll", "System.Data.dll", "System.Windows.Forms.dll"} 'Any referenced dll's
    Dim Compiler As New VbCompiler(SourceCode, Dlls)
    Dim CodeAssembly As Assembly = Compiler.Compile
    If Compiler.Successful Then
        Dim instance As Object = CodeAssembly.CreateInstance("TestCode.Class1")
        Dim CodeType As Type = instance.GetType
        Dim Info As MethodInfo = CodeType.GetMethod("ShowMessage")
        Info.Invoke(instance, Nothing)
    Else
        For Each i As CompilerError In Compiler.Errors
            MsgBox(i.ErrorText)
        Next
    End If

txtCode.text =:

Imports System.Windows.Forms
Namespace TestCode
    Class Class1
        Sub ShowMessage()
            MessageBox.Show("Test")
        End Sub
    End Class
End Namespace

这完美无缺。我想知道如何将参数传递给函数。即

txtCode.text =:

Imports System.Windows.Forms
Namespace TestCode
    Class Class1
        Sub ShowMessage(ByVal x As String)
            MessageBox.Show(x)
        End Sub
    End Class
End Namespace 

我想用一个字符串作为参数运行'ShowMessage'函数,(“Test”)作为例子。

我很确定它是在以下几行:

    Dim Info As MethodInfo = CodeType.GetMethod("ShowMessage")
    Info.Invoke(instance, Nothing)

但我无法让它发挥作用。

1 个答案:

答案 0 :(得分:0)

您需要传递字符串值。

 Info.Invoke(instance, New Object(){"Test"})

编辑:两个论点

 Info.Invoke(instance, New Object(){"First","Second"})