按名称获取变量值

时间:2014-01-18 21:58:14

标签: vb.net reflection system.reflection

有谁知道通过名称动态获取参数值的任何方法?我正在尝试创建一个动态传递其参数的函数。我正在使用Reflection来获取参数的名称,但似乎无法弄清楚如何获取传递给函数的值。

示例:

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

2 个答案:

答案 0 :(得分:0)

以下方法将返回属性(给定属性名称)值:

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

希望有所帮助

答案 1 :(得分:-1)

如果你想打印' Xyzzy'那么


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