void Main(){测试 t = 新测试{A = "一",B = "b",//<-- 错误的尾随逗号};}公开课测试{公共字符串 A { 获取;放;}公共字符串 B { 获取;放;}}
我在我的代码中发现了很多上面的错字.我总是对编译器似乎并不关心这一点感到惊讶.为什么上面不是语法错误?它有什么实际有效的用途吗?
我在我的代码中发现了很多上面的错字.我总是对编译器似乎并不关心这一点感到惊讶.为什么上面不是语法错误?
因为设计 C# 语法语法的人足够聪明,可以从其他编程语言中吸取教训,不允许使用悬空的逗号,从而使那些语言的程序员不断受到刺激.p>
例如,ECMAScript (JavaScript) 最初对这个问题保持沉默,因此一些实现(Firefox 中的 SpiderMonkey、Opera 的 JavaScript 等)自然而然地允许它们,而其他实现(微软的 JScript)则不允许.因此,这导致了这里和其他地方的一连串为什么这在 IE 中不起作用"的问题.(幸运的是,ECMAScript 5 明确允许它们,并且 IE8 最终在对象初始化器中支持它们——IE8 仍然以非标准方式处理数组初始化器,但公平地说,那些悬空的逗号也仅在 ECMAScript 5 中得到澄清.)
您在 C# 语法的许多其他地方也发现了这一点,例如枚举和数组初始值设定项.
void Main()
{
Test t = new Test
{
A = "a",
B = "b", // <-- erroneous trailing comma
};
}
public class Test
{
public string A { get; set; }
public string B { get; set; }
}
I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror? Is there any actually valid use for it?
I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror?
Because the people designing the C# syntax grammar were smart enough to learn the lessons from other programming languages which didn't allow the dangling comma, to the constant irritation of programmers in those languages.
For example, ECMAScript (JavaScript) was silent on the issue initially, and so naturally some implementations (SpiderMonkey in Firefox, Opera's JavaScript, etc.) allowed them while others (Microsoft's JScript) didn't. And so this led to a spate of "why doesn't this work in IE" questions here and elsewhere. (Fortunately, ECMAScript 5 explicitly allows them, and IE8 finally supports them in object initializers -- IE8 still treats array initializers in a non-standard way, though to be fair the dangling comma for those was only clarified in ECMAScript 5, too.)
You find this in lots of other places in the C# grammar too, like enums and array initializers.
这篇关于内联属性初始化和尾随逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!