Inline property initialisation and trailing comma(内联属性初始化和尾随逗号)
问题描述
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.
这篇关于内联属性初始化和尾随逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:内联属性初始化和尾随逗号
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01