我想创建一个执行以下操作的简单函数:
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
用法:
Dim x As New Person
SetValue(x, Function(p) p.FirstName, "John Doe")
答案 0 :(得分:1)
实际上非常简单:
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