Get the value of a variable by name

Does anyone know of any way to dynamically get a parameter value by name? I am trying to create a function that will dynamically pass its parameters. I use Reflection to get the name of the parameter, but I can't figure out how to get the value that was passed to the function.

Example:

Imports System.Reflection

Console.WriteLine(Test("Xyzzy"))
' Should print: Xyzzy

Function Test(ByVal x as String)
  Return GetValueByName(MethodBase.GetCurrentMethod.GetParameters(0).Name))
End Function
+4
source share
2 answers

The following method will return the property (given the name of the property):

Public Function GetPropertyValue(propertyName As String) As Object

        Dim pi As System.Reflection.PropertyInfo = Me.GetType().GetProperty(propertyName)

        If (Not pi Is Nothing) And pi.CanRead Then
            Return pi.GetValue(Me, Nothing)
        End If

        Dim a As Type() = Nothing
        Dim mi As System.Reflection.MethodInfo = Me.GetType().GetMethod("Get" + propertyName, a)

        If Not mi Is Nothing Then
            Return mi.Invoke(Me, Nothing)
        End If

        Return Nothing
    End Function

Hope this helps

0
source

If you want to print "Xyzzy" then


Console.WriteLine(Test("Xyzzy"))
' Should print: Xyzzy
Function Test(ByVal x as String)
  Return x                 
End Function

0
source

All Articles