[英]Creating delegate dynamically
I'm trying to create delegate dynamically, but it's not going my way :S 我正在尝试动态创建委托,但没有按照我的方式进行: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
When I compile this code and debug, I got exception at this line. 当我编译此代码并进行调试时,此行出现异常。
Dim dgHelloB As [Delegate] = [Delegate].CreateDelegate(CDelegate, miHelloB)
Exception Message: Error binding to target method. 异常消息:错误绑定到目标方法。 How can I fix this code??
我该如何解决此代码? Anyone please help.
有人请帮忙。
I think that you are having instance method Invoke
, in this case you have to following Overload of CreateDelegate, 我认为您拥有实例方法
Invoke
,在这种情况下,您必须遵循CreateDelegate的Overload,
public static Delegate CreateDelegate(
Type type,
Object target/*your class instance CTest */,
string method
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.