none
Invoke a method in a module using Reflection in VB.NET RRS feed

  • Question

  • Hi,

    I have a module in a .NET Project.  I could load the module using reflection, in the dll.  I need to know how to invoke, a method in the module.

    Thanks in advance,
    Baburaj
    Wednesday, November 25, 2009 6:46 AM

Answers

  • The following example demonstrates dynamic method lookup using reflection. Note that you cannot use the MethodInfo object from the base class to invoke the overridden method in the derived class, because late binding cannot resolve overrides.

    Public Class A
       Public Overridable Function method() As Integer
          Return 0
       End Function
    End Class
    
    Public Class B
       Public Overridable Function method() As Integer
          Return 1
       End Function
    End Class
    
    Class Example
    
       Public Shared Function Demo(ByVal outputBlock As System.Windows.Controls.TextBlock) As Integer
          outputBlock.Text &= "Reflection.MethodInfo" & vbCrLf
          outputBlock.Text &= vbCrLf
          Dim MyA As New A()
          Dim MyB As New B()
    
          'Get the Type and MethodInfo
          Dim MyTypea As Type = GetType(A)
          Dim Examplea As MethodInfo = MyTypea.GetMethod("method")
    
          Dim MyTypeb As Type = GetType(B)
          Dim Exampleb As MethodInfo = MyTypeb.GetMethod("method")
    
          'Get and display the Invoke method
          outputBlock.Text &= String.Format("First method - {0} returns {1}", MyTypea.FullName, _
              Examplea.Invoke(MyA, Nothing).ToString()) & vbCrLf
          outputBlock.Text &= String.Format("Second method - {0} returns {1}", MyTypeb.FullName, _
             Exampleb.Invoke(MyB, Nothing).ToString()) & vbCrLf
          Return 0
       End Function
    End Class
    
    ' This code produces output similar to the following:
    '
    'First method - SilverlightApplication.A returns 0
    'Second method - SilverlightApplication.B returns 1

    Regards,

    Jai

    Wednesday, November 25, 2009 7:46 AM