【问题标题】:Get variable value by name按名称获取变量值
【发布时间】:2014-02-08 05:32:35
【问题描述】:

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

例子:

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

【问题讨论】:

  • 你能举一个更好的例子,也许是它背后的目标吗?在这种情况下,我会说:返回 x 的值
  • 目前在 .NET 中是不可能的。见this question
  • 如果这段代码进入你希望检查的方法相同,那么它肯定不需要是动态的吗?作为该方法的作者,您已经知道所有参数。
  • 我将创建许多函数,这些函数将获取它们的参数并调用另一个类中的例程。我只是在寻找一种方法来简化这些函数,而不必为每个函数的每个参数编写参数名称。如果参数发生变化等也会有所帮助。
  • 如果参数基于外部例程中的参数,那么您不是已经硬编码了可能通过自己定义函数而改变的信息吗?在这种情况下,最好自己生成源代码,例如通过T4 template

标签: vb.net reflection system.reflection


【解决方案1】:

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

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

希望对你有帮助

【讨论】:

    【解决方案2】:

    如果你想打印'Xyzzy'然后

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      相关资源
      最近更新 更多