有没有一种简单的方法来解析(拉姆达EX pression)字符串转换为Action委托? [英] Is there an easy way to parse a (lambda expression) string into an Action delegate?

查看:276
本文介绍了有没有一种简单的方法来解析(拉姆达EX pression)字符串转换为Action委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有改变根据传给它的动作代表一个账户对象的方法:

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

public static void AlterAccount(string AccountID, Action<Account> AccountAction) {
  Account someAccount = accountRepository.GetAccount(AccountID);
  AccountAction.Invoke(someAccount);
  someAccount.Save();
}

这按预期工作...

AlterAccount("Account1234", a => a.Enabled = false);

...但现在我想尝试做的是有这样的方法:

...but now what I'd like to try and do is have a method like this:

public static void AlterAccount(string AccountID, string AccountActionText) {
  Account someAccount = accountRepository.GetAccount(AccountID);
  Action<Account> AccountAction = MagicLibrary.ConvertMagically<Action<Account>>(AccountActionText);
  AccountAction.Invoke(someAccount);
  someAccount.Save();
}

然后,它可以使用,如:

It can then be used like:

AlterAccount("Account1234", "a => a.Enabled = false");

禁用帐户Account1234。

to disable account "Account1234".

我有一个看<一href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">linq动态查询库,这似乎做或多或少是我想要的,但对于Func键类型的代表,和我的前pression树等知识不是很够很好的工作,如何实现我想要的。

I've had a look at the linq dynamic query library, which seems to do more or less what I want but for Func type delegates, and my knowledge of Expression trees etc isn't quite good enough to work out how to achieve what I want.

有没有一种简单的方法做我想做的,还是我需要学习EX pressions正确,写了code负载?

Is there an easy way to do what I want, or do I need to learn expressions properly and write a load of code?

(我想这样做的原因是为了让从PowerShell脚本批量更新帐户对象的一种简单的方法,用户可以指定一个lambda EX pression进行更改。)

(The reason I want to do this is to allow an easy way of bulk updating account objects from a powershell script where the user can specify a lambda expression to perform the changes.)

推荐答案

您可以试试这个:的动态LAMBDA防爆pressions使用独立的AppDomain

它编译使用codeDOM编译器一个lambda EX pression。为了处理被创建的内存组件,编译器在一个孤立的的AppDomain 运行。对于通过前pression通过域边界,它必须被序列化。唉,防爆pression&LT;&GT; 不是序列化。所以,一招,必须使用。所有的细节都在后解释说。

It compiles a lambda expression using CodeDOM compiler. In order to dispose the in-memory assembly that gets created, the compiler runs on an isolated AppDomain. For the passing the expression through the domain boundary, it has to be serialized. Alas, Expression<> is not Serializable. So, a trick has to be used. All the details are explained in the post.

我该组件的作者,顺便说一句。我很想听到它您的反馈意见。

I'm the author of that component, by the way. I would like very much to hear your feedback from it.

这篇关于有没有一种简单的方法来解析(拉姆达EX pression)字符串转换为Action委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆