带有linq表达式的动态属性设置器?

时间:2011-01-05 06:55:18

标签: vb.net lambda properties linq-expressions

我想创建一个执行以下操作的简单函数:

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")

1 个答案:

答案 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