开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜