为什么表达式树不能包含命名参数规范? [英] Why can't an expression tree contain a named argument specification?
问题描述
使用AutoMapper,我找到了一个适合命名参数的地方:
Using AutoMapper, I hit a place where a named argument would've fit very nicely:
.ForMember(s => s.MyProperty, opt => opt.MapFrom(s => BuildMyProperty(s, isAdvanced: false)))
但是编译器对我大喊:
表达式树可能不包含命名参数规范
An expression tree may not contain a named argument specification
所以我不得不恢复为:
.ForMember(s => s.MyProperty, opt => opt.MapFrom(s => BuildMyProperty(s, false)))
有人知道为什么在这种情况下编译器不允许命名参数吗?
Does anyone know why the compiler disallows named arguments in this situation?
推荐答案
考虑一下以下:
static int M() { Console.Write("M"); return 1; }
static int N() { Console.Write("N"); return 2; }
static int Q(int m, int n) { return m + n; }
...
Func<int> f = ()=>Q(n : N(), m: M());
Expression<Func<int>> x = ()=>Q(n : N(), m: M());
Func<int> fx = x.Compile();
Console.WriteLine(f());
Console.WriteLine(fx());
您同意我希望最后两行必须做完全相同的事情,对吗?现在要打印 NM3
。
You agree I hope that the last two lines must do exactly the same thing, right? Which is to print NM3
.
现在,表达式树库调用什么,希望表达式树转换生成确保这一点?没有了!因此,我们面临以下选择:
Now, what expression tree library calls would you like the expression tree conversion to generate that ensure this? There are none! We are therefore faced with the following choices:
- 在表达式树库中实现该功能。在表达式树降低引擎中添加一个转换,以保留命名参数的执行顺序。在
Compile
方法中实现将执行顺序考虑在内的代码。 - 使
x =()=> Q(n:N(),m:M());
实际上被实现为x =()=> Q(M(),N());
,并且与非表达式树版本不兼容。 - 禁止在表达式树中使用命名参数。为此,请执行一条错误消息。
- Implement the feature in the expression tree library. Add a transformation in the expression tree lowering engine that preserves the order of execution of the named arguments. Implement code in the
Compile
method that takes the execution order into account. - Make
x = ()=>Q(n : N(), m: M());
actually be implemented asx = ()=>Q(M(), N());
and be incompatible with the non-expression-tree version. - Disallow named arguments in expression trees. Implement an error message to that effect.
(1)很好,但是很昂贵。 (2)是非入门者;我们不能凭良心介绍这种陷阱。 (3)价格便宜但令人讨厌。
(1) is nice, but expensive. (2) is a non-starter; we can't in good conscience introduce this kind of "gotcha". (3) is cheap but irritating.
我们选择了(3)。
这篇关于为什么表达式树不能包含命名参数规范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!