gpt4 book ai didi

vb.net - 按名称获取变量值

转载 作者:行者123 更新时间:2023-12-01 06:50:38 36 4
gpt4 key购买 nike

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

例子:

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

最佳答案

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

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

希望能帮助到你

关于vb.net - 按名称获取变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210421/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com