循环属性 vb.net [英] Loop through properties vb.net
问题描述
晚安,
我正在从 API 中提取数据,该 API 将记录公开为类的属性,因此示例如下
I am extracting data from a API which exposes records as properties of the class so an example would be
For Each entry As Webservice.Names In objResponse.results
string = string & "'firstname'=" & entry.firstname
string = string & "'surname'=" & entry.surname
next
现在我们在网络服务中有大约 50 个实体,每个实体至少有 10 个字段",我的问题是我可以以其他方式公开属性吗?
now we have about 50 entities in the webservice, and each has at least 10 "fields" my question is can I expose properties any other way ?
即我可以
For Each entry As Webservice.Names In objResponse.results
for each prop in entry.properties
string = string & "'" & prop.name & "'=" & entry.fields(prop.name)
next
next
或类似的,我似乎无法公开上面的属性,但我真的在寻找一种方法,我不必针对字符串手动键入每个属性以插入到数据库中.
or similar, i can't seem to expose the properties above, but really looking for a way that i don't have to hand type every property against the string for inserting to the database.
关于如何在 VB 中实现这一点的任何想法,如果属性没有像上面的例子那样公开
any thoughts on how to achieve this within VB if the properties aren't exposed as above example
提前致谢
推荐答案
您可以使用反射获取属性及其值的列表.
You can get list of properties and their values using Reflection.
For Each entry As Webservice.Names In objResponse.results
for each prop in entry.GetType().GetProperties()
' use System.Reflection.BindingFlags to filter it.
string = string & "'" & prop.name & "'=" & prop.GetValue(entry,nothing)
' use entry as first argument. it requires an instance of object to get 'property value
next
next
这篇关于循环属性 vb.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!