反映参数名称:滥用 C# lambda 表达式还是语法高明? [英] Reflecting parameter name: abuse of C# lambda expressions or syntax brilliance?
问题描述
我正在查看 MvcContrib Grid 组件,我很着迷,但同时被 网格语法:
I am looking at the MvcContrib Grid component and I'm fascinated, yet at the same time repulsed, by a syntactic trick used in the Grid syntax:
.Attributes(style => "width:100%")
上面的语法将生成的 HTML 的样式属性设置为 width:100%
.现在如果你注意的话,'style' 没有被指定.它是从表达式中参数的名称推导出来的!我不得不深入研究并发现魔法"发生的地方:
The syntax above sets the style attribute of the generated HTML to width:100%
. Now if you pay attention, 'style' is nowhere specified. It is deduced from the name of the parameter in the expression! I had to dig into this and found where the 'magic' happens:
Hash(params Func<object, TValue>[] hash)
{
foreach (var func in hash)
{
Add(func.Method.GetParameters()[0].Name, func(null));
}
}
因此,代码确实使用正式的、编译时的参数名称来创建属性名称-值对的字典.结果语法结构确实非常具有表现力,但同时也非常危险.
So indeed, the code is using the formal, compile time, name of parameters to create the dictionary of attribute name-value pairs. The resulted syntax construct is very expressive indeed, but at the same time very dangerous.
lambda 表达式的一般用途允许替换使用的名称而不会产生副作用.我在一本书中看到一个例子,上面写着 collection.ForEach(book => Fire.Burn(book))
我知道我可以在我的代码中编写 collection.ForEach(log =>;Fire.Burn(log))
和意思是一样的.但是突然之间有了 MvcContrib Grid 语法,我发现代码会主动查看并根据我为变量选择的名称做出决定!
The general use of lambda expressions allows for replacement of the names used without side effect. I see an example in a book that says collection.ForEach(book => Fire.Burn(book))
I know I can write in my code collection.ForEach(log => Fire.Burn(log))
and it means the same thing. But with the MvcContrib Grid syntax here all of a sudden, I find code that actively looks and makes decisions based on the names I choose for my variables!
那么这是 C# 3.5/4.0 社区和 lambda 表达式爱好者的常见做法吗?还是我不应该担心的流氓一招特立独行?
So is this common practice with the C# 3.5/4.0 community and the lambda expressions lovers? Or is a rogue one trick maverick I shouldn't worry about?
推荐答案
这具有较差的互操作性.例如,考虑这个 C# - F# 示例
This has poor interop. For example, consider this C# - F# example
C#:
public class Class1
{
public static void Foo(Func<object, string> f)
{
Console.WriteLine(f.Method.GetParameters()[0].Name);
}
}
F#:
Class1.Foo(fun yadda -> "hello")
结果:
arg"被打印出来(不是yadda").
"arg" is printed (not "yadda").
因此,库设计者应该避免这些类型的滥用",或者如果他们想要跨 .网络语言.
As a result, library designers should either avoid these kinds of 'abuses', or else at least provide a 'standard' overload (e.g. that takes the string name as an extra parameter) if they want to have good interop across .Net languages.
这篇关于反映参数名称:滥用 C# lambda 表达式还是语法高明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!