Access property using its name in vb.net

前端 未结 2 2064
臣服心动
臣服心动 2020-12-10 04:36

For example:

Sub Test()
  Dim car as new MyCar
  car.chassis.wheel.radius = 15
  Console.WriteLine(car.chassis.wheel.radius)    
End Sub

相关标签:
2条回答
  • 2020-12-10 04:57

    You can, but not as concise as in your question.

    This function will get any property of any object by name.

    Public Function GetPropertyValue(ByVal obj As Object, ByVal PropName As String) As Object
        Dim objType As Type = obj.GetType()
        Dim pInfo As System.Reflection.PropertyInfo = objType.GetProperty(PropName)
        Dim PropValue As Object = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
        Return PropValue
    End Function
    

    I leave error handling to you. And any consequences :)

    0 讨论(0)
  • 2020-12-10 05:06

    Yes you can very easily:

    Dim radius As Integer = CallByName(car.chassis.wheel, "radius", Microsoft.VisualBasic.CallType.Get, Nothing)
    

    See this Microsoft page for reference.

    0 讨论(0)
提交回复
热议问题