简体   繁体   English

动态创建委托

[英]Creating delegate dynamically

I'm trying to create delegate dynamically, but it's not going my way :S 我正在尝试动态创建委托,但没有按照我的方式进行:S

Implementation 实作

  1. Create CodeDomProvider objects to compile source code. 创建CodeDomProvider对象以编译源代码。
  2. Compiled assembly(result) will be stored in memory. 编译后的程序集(结果)将存储在内存中。 (Not my HDD) (不是我的硬盘)
  3. Get type from result 从结果中获取类型
  4. Create delegate with Delegate.CreateDelegate Method. 使用Delegate.CreateDelegate方法创建委托。

Source Code to be compiled by CodeDomProvider 由CodeDomProvider编译的源代码

Imports System

Public Class CTest

    Public Delegate Function HelloB() As Int32

End Class

Source Code 源代码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM