我正在尝试动态创建委托,但它不是我的方式:S
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)
异常消息:绑定到目标方法时出错。 我该如何修复这段代码? 有人请帮忙。
答案 0 :(得分:0)
我认为您正在使用实例方法Invoke
,在这种情况下,您必须遵循Overload of CreateDelegate,
public static Delegate CreateDelegate(
Type type,
Object target/*your class instance CTest */,
string method
)