开发者

Dynamic property setter with linq expressions?

开发者 https://www.devze.com 2023-02-02 19:04 出处:网络
I want to 开发者_Python百科create a simple function that does the following: Sub SetValue(Of TInstance As Class, TProperty)(

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

精彩评论

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