简体   繁体   中英

Creating delegate dynamically

I'm trying to create delegate dynamically, but it's not going my way :S

Implementation

  1. Create CodeDomProvider objects to compile source code.
  2. Compiled assembly(result) will be stored in memory. (Not my HDD)
  3. Get type from result
  4. Create delegate with Delegate.CreateDelegate Method.

Source Code to be compiled by 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,

public static Delegate CreateDelegate(
    Type type,
    Object target/*your class instance CTest */,
    string method
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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