在 vb.net 中使用其名称访问属性 [英] Access property using its name in vb.net

查看:50
本文介绍了在 vb.net 中使用其名称访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

所以问题是.是否可以使用其字符串名称访问该属性,例如东西(car.chassis.wheel.radius")= 15?

So question is. Is it possible to access the property using its string name like Something("car.chassis.wheel.radius") = 15?

推荐答案

你可以,但不像你的问题那么简洁.

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 :)

这篇关于在 vb.net 中使用其名称访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆