我正在尝试动态创建委托,但它不是我的方式:S
执行
- 创建 CodeDomProvider 对象以编译源代码。
- 编译的程序集(结果)将存储在内存中。(不是我的硬盘)
- 从结果中获取类型
- 使用 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)
异常消息:绑定到目标方法时出错。我该如何修复此代码?任何人请帮忙。