在 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
Access property using its name in vb.net
提问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页面以供参考。