Is there an easy way to parse a (lambda expression) string into an Action delegate?

前端 未结 4 526
谎友^
谎友^ 2020-12-05 11:18

I have a method that alters an \"Account\" object based on the action delegate passed into it:

public static void AlterAccount(string AccountID, Action

        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 12:19

    The Dynamic LINQ library is a fine choice, as it'll generate expressions you can compile to code in a lightweight fashion.

    The example you provided actually produces a boolean -- so you should be able to ask for a Func and it might sort it out.

    Edit: This of course is wrong, as Expressions don't have assignment in them at all.

    So, another potential way is to take two lambdas. One to find the property you want, one to provide a value:

    (a => a.AccountId), (a => true)

    Then use reflection to set the property referenced in the first lambda with the result of the second one. Hackish, but it's still probably lightweight compared to invoking the C# compiler.

    This way you don't have to do much codegen yourself - the expressions you get will contain most everything you need.

提交回复
热议问题