我有一个方法,根据传递的操作委托修改一个“帐户”对象:
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);
... 但是现在我想尝试的是有一个像这样的方法:
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();
}
然后可以像这样使用:
AlterAccount("Account1234", "a => a.Enabled = false");
禁用名为 "Account1234" 的账户。
我查看了linq动态查询库,它似乎可以做到我想要的,但只适用于Func类型委托,而且我的表达式树等方面的知识还不够好,无法找出如何实现我想要的功能。
有没有一种简单的方法来达到我想要的效果,或者我需要学习表达式并编写大量的代码?
(我之所以想这样做,是为了允许用户从PowerShell脚本轻松地批量更新账户对象,其中用户可以指定Lambda表达式来执行更改。)
MagicLibrary.ConvertMagically
。 - The Muffin Man