在 vb.net 中使用其名称访问属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2942699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:54:11  来源:igfitidea点击:

Access property using its name in vb.net

vb.netreflection

提问by rqm.yorik

For example:

例如:

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

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

所以问题是。是否可以使用它的字符串名称访问该属性,如Something("car.chassis.wheel.radius") = 15?

回答by Miroslav Zadravec

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

我把错误处理留给你。以及任何后果:)

回答by pnizzle

Yes you can very easily:

是的,您可以很容易地:

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

See this Microsoftpage for reference.

请参阅此 Microsoft页面以供参考。