2

我正在尝试动态创建委托,但它不是我的方式:S

执行

  1. 创建 CodeDomProvider 对象以编译源代码。
  2. 编译的程序集(结果)将存储在内存中。(不是我的硬盘)
  3. 从结果中获取类型
  4. 使用 Delegate.CreateDelegate 方法创建委托。

由 CodeDomProvider 编译的源代码

Imports System

Public Class CTest

    Public Delegate Function HelloB() As Int32

End Class

源代码

Dim VBCompiler As CodeDom.Compiler.CodeDomProvider = CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"),
    CParam As New CodeDom.Compiler.CompilerParameters,
    CResult As CodeDom.Compiler.CompilerResults

CParam.GenerateExecutable = False
CParam.GenerateInMemory = True
CParam.IncludeDebugInformation = False
CParam.ReferencedAssemblies.Add("System.dll")

CResult = VBCompiler.CompileAssemblyFromSource(CParam, TextBox1.Text)

Dim CompiledAssembly As System.Reflection.Assembly = CResult.CompiledAssembly
Dim CDelegate As Type = CompiledAssembly.GetType("CTest+HelloB")
If Not IsNothing(CDelegate ) Then

    Dim miHelloB As System.Reflection.MethodInfo = CDelegate .GetMethod("Invoke")
    Dim dgHelloB As [Delegate] = [Delegate].CreateDelegate(CDelegate, miHelloB)
    dgHelloB.DynamicInvoke()

End If

当我编译这段代码并调试时,我在这一行遇到了异常。

Dim dgHelloB As [Delegate] = [Delegate].CreateDelegate(CDelegate, miHelloB)

异常消息:绑定到目标方法时出错。我该如何修复此代码?任何人请帮忙。

4

1 回答 1

0

我认为你有实例方法Invoke,在这种情况下你必须遵循 CreateDelegate 的重载,

public static Delegate CreateDelegate(
    Type type,
    Object target/*your class instance CTest */,
    string method
)
于 2013-10-10T13:34:10.893 回答