poseur de propriété dynamique avec des expressions LINQ?
-
25-09-2019 - |
Question
Je veux créer une fonction simple qui effectue les opérations suivantes:
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
Utilisation:
Dim x As New Person
SetValue(x, Function(p) p.FirstName, "John Doe")
La solution
Il est en fait assez 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow