Feb 22, 2017 11:56 AM
(This post was last modified: Feb 22, 2017 11:58 AM by Barret.)
This is a very small yet powerful little invoker that wraps around a type and caches all methods found within that type.
As easy as calling them by name (String) with parameters that don't necessarily have to match, it is forgiven meaning
it will try to convert parameters that can be converted in the signature it requires.
The MethodAttributes parameter is there to filter those methods that are desired, such Shared and Public methods only.
This wrapper is part of a bigger project i'm working on but has many uses for other projects.
Remark: It does not support multiple signatures of the same method
Usage:
As easy as calling them by name (String) with parameters that don't necessarily have to match, it is forgiven meaning
it will try to convert parameters that can be converted in the signature it requires.
The MethodAttributes parameter is there to filter those methods that are desired, such Shared and Public methods only.
This wrapper is part of a bigger project i'm working on but has many uses for other projects.
Remark: It does not support multiple signatures of the same method
Usage:
PHP Code
<?php
dim Invoker as New Invoker(SomeType, MethodAttributes.Public Or MethodAttributes.Static)
Dim Result as object = Invoker.Invoke("MyFunction",Arg0,Arg1,Etc...)
PHP Code
<?php
Imports System.Reflection
Public Class Invoker
Inherits Dictionary(Of String, MethodInfo)
Public Property Type As Type
Sub New(Type As Type, MethodAttributes As MethodAttributes)
Me.Type = Type
For Each m As MethodInfo In Me.Type.GetMethods.Where(Function(x) x.Attributes = MethodAttributes)
Me.Add(m.Name.ToLower, m)
Next
End Sub
Public Function Invoke(Name As String, ParamArray Parameters() As Object) As Object
If (Me.ContainsKey(Name.ToLower)) Then
If (Me.HasSignature(Me(Name.ToLower), Parameters)) Then
Return Me(Name.ToLower).Invoke(Me.Type, Parameters)
Else
Return Me(Name.ToLower).Invoke(Me.Type, Me.TryConvertParamaters(Me(Name.ToLower), Parameters))
End If
End If
Return New Object
End Function
Private Function TryConvertParamaters(Target As MethodInfo, Parameters() As Object) As Object()
Dim Params As New List(Of Object)
If (Parameters.Count = Target.GetParameters.Count) Then
For i As Integer = 0 To Parameters.Count - 1
If (Parameters(i).GetType IsNot Target.GetParameters(i).ParameterType) Then
Params.Add(Convert.ChangeType(Parameters(i), Target.GetParameters(i).ParameterType))
Else
Params.Add(Parameters(i))
End If
Next
End If
Return Params.ToArray
End Function
Private Function HasSignature(Target As MethodInfo, Parameters() As Object) As Boolean
If (Parameters.Count <> Target.GetParameters.Count) Then Return False
For i As Integer = 0 To Parameters.Count - 1
If (Parameters(i).GetType IsNot Target.GetParameters(i).ParameterType) Then
Return False
End If
Next
Return True
End Function
End Class


