VB .NET 通过字符串值访问类属性 [英] VB .NET Access a class property by string value
问题描述
我有一个函数可以更新数据库中的客户端.传入客户端对象以及应更新的字段/属性字符串数组.我需要一种根据数组中的内容访问客户端对象中的每个属性的方法.基本上,我正在寻找与此 javascript 等效的 VB .NET:
I have a function that updates a Client in the database. A client object is passed in, along with a string array of fields/properties that should be updated. I need a way of accessing each property in the client object, based on what is in the array. Basically, I am looking for the VB .NET equivalent to this javascript:
var fields = ["Firstname","Lastname","DOB"];
for(field in fields)
{
var thisField = fields[field];
client[thisField] = obj[thisField];
}
任何帮助将不胜感激!感谢堆栈.
Any help will be greatly appreciated! Thanks Stack.
推荐答案
您可以使用反射 这样做.在不了解您的数据对象是如何设置的情况下,我无法给您提供一个完美的示例,但总体思路如下:
You can use Reflection to do this. Without knowing more about how your data objects are set up, I can't give you a perfect example, but here's the general idea:
Dim myPerson As New Person
myPerson.FirstName = "John"
myPerson.LastName = "Doe"
myPerson.DOB = #1/1/2000#
Dim myUpdates As New Dictionary(Of String, Object)
myUpdates.Add("FirstName", "Adam")
myUpdates.Add("LastName" , "Maras")
myUpdates.Add("DOB" , #1/1/1990#)
Dim personType As Type = GetType(Person)
For Each kvp As KeyValuePair(Of String, Object) In myUpdates
Dim propInfo As PropertyInfo = personType.GetProperty(kvp.Key)
If propInfo IsNot Nothing Then
propInfo.SetValue(myPerson, kvp.Value)
End If
Next
这篇关于VB .NET 通过字符串值访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!