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)

  '...
End Sub

使用法:

Dim x As New Person
SetValue(x, Function(p) p.FirstName, "John Doe")
4

1 に答える 1

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

于 2011-01-05T07:07:51.357 に答える