Dynamic property setter with linq expressions?
I want to 开发者_Python百科create a simple function that does the following:
Sub SetValue(Of TInstance As Class, TProperty)(
ByVal instance As TInstance,
ByVal [property] As Expression(Of Func(Of TInstance, TProperty)),
ByVal value As TProperty)
'...
End Sub
Usage:
Dim x As New Person
SetValue(x, Function(p) p.FirstName, "John Doe")
It's actually pretty simple:
Sub SetValue(Of TInstance As Class, TProperty)(
ByVal instance As TInstance,
ByVal [property] As Expression(Of Func(Of TInstance, TProperty)),
ByVal value As TProperty)
'TODO: validate nulls
If [property].Body.NodeType <> ExpressionType.MemberAccess Then _
Throw New ArgumentException("Invalid lambda expression.", "property")
Dim body = DirectCast([property].Body, MemberExpression)
Dim member = DirectCast(body.Member, PropertyInfo)
member.SetValue(instance, value, Nothing)
End Sub
HTH
精彩评论