VB .NET Access a class property by string value
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 t开发者_运维百科he 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
精彩评论