我看着MvcContrib网格组件,我很着迷,但同时又被网格语法中使用的语法技巧所排斥:

.Attributes(style => "width:100%")

上面的语法将生成的HTML的样式属性设置为width:100%。如果你注意的话,'style'并没有被指定。它是从表达式中参数的名称推导出来的!我必须深入研究这个问题,找到“魔法”发生的地方:

Hash(params Func<object, TValue>[] hash)
{
    foreach (var func in hash)
    {
        Add(func.Method.GetParameters()[0].Name, func(null));
    }
}

因此,代码确实使用了正式的、编译时的参数名称来创建属性名称-值对的字典。生成的语法结构确实非常具有表现力,但同时也非常危险。

lambda表达式的一般用法允许替换所使用的名称而不产生副作用。我在一本书上看到一个例子,上面写着收藏。我知道我可以在我的代码集合中写。ForEach(log => fire。burn (log))它的意思是一样的。但是使用这里的MvcContrib Grid语法,我突然发现代码可以根据我为变量选择的名称主动查找并做出决定!

那么这是c# 3.5/4.0社区和lambda表达式爱好者的普遍做法吗?还是说,我不应该担心一个流氓的诡计特立独行?


当前回答

该代码非常聪明,但它可能会导致比它解决的问题更多的问题。

正如您所指出的,现在在参数名称(样式)和HTML属性之间存在模糊的依赖关系。没有编译时检查。如果参数名称输入错误,页面可能不会有运行时错误消息,但很难找到逻辑错误(没有错误,但行为不正确)。

更好的解决方案是拥有一个可以在编译时检查的数据成员。所以不要这样:

.Attributes(style => "width:100%");

带有Style属性的代码可以被编译器检查:

.Attributes.Style = "width:100%";

甚至:

.Attributes.Style.Width.Percent = 100;

对于代码的作者来说,这是更多的工作,但是这种方法利用了c#强大的类型检查能力,这有助于在第一时间防止错误进入代码。

其他回答

恕我直言,这是一种很酷的方式。我们都喜欢将类命名为控制器将使其成为MVC中的控制器,对吧?所以在某些情况下,命名确实很重要。

这里的意图也很明确。很容易理解,.Attribute(book= > "something")将导致book="something", .Attribute(log= > "something")将导致log="something"

我想如果你把它当作一种惯例来对待,那应该不成问题。我的观点是,只要能让你写更少的代码,让你的意图更明显,那就是一件好事。

我更喜欢

Attributes.Add(string name, string value);

它更加明确和标准,使用lambdas什么也得不到。

如果方法(func)名称选择得当,那么这是避免维护头痛的好方法(例如:添加一个新的func,但忘记将其添加到函数参数映射列表中)。当然,你需要对它进行大量的文档记录,你最好从该类函数的文档中自动生成参数的文档……

All this ranting about "horridness" is a bunch of long-time c# guys overreacting (and I'm a long-time C# programmer and still a very big fan of the language). There's nothing horrible about this syntax. It is merely an attempt to make the syntax look more like what you're trying to express. The less "noise" there is in the syntax for something, the easier the programmer can understand it. Decreasing the noise in one line of code only helps a little, but let that build up across more and more code, and it turns out to be a substantial benefit.

This is an attempt by the author to strive for the same benefits that DSL's give you -- when the code just "looks like" what you're trying to say, you've reached a magical place. You can debate whether this is good for interop, or whether it is enough nicer than anonymous methods to justify some of the "complexity" cost. Fair enough ... so in your project you should make the right choice of whether to use this kind of syntax. But still ... this is a clever attempt by a programmer to do what, at the end of the day, we're all trying to do (whether we realize it or not). And what we're all trying to do, is this: "Tell the computer what we want it to do in language that is as close as possible to how we think about what want it to do."

使软件更易于维护、更准确的关键在于,我们能够更接近于用我们内心认为的方式向计算机表达指令。

编辑:我曾经说过“使软件更具可维护性和准确性的关键”,这是一种疯狂的天真和夸张的独角兽观点。我把它改成了“钥匙”。

的确,它看起来像Ruby =),至少对我来说,使用静态资源进行以后的动态“查找”不适合api设计的考虑,希望这个聪明的技巧是可选的api。

当你不需要添加键来设置值时,我们可以继承(或不继承)IDictionary并提供一个像php数组一样的索引器。它将是.net语义的有效使用,而不仅仅是c#,并且仍然需要文档。

希望这能有所帮助