内联财产初始化和尾随逗号 [英] Inline property initialisation and trailing comma

查看:110
本文介绍了内联财产初始化和尾随逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 无效的主要()
{
测试T =新的测试
{
A =A,$ B $条b B =b,//< - 错误后面的逗号
};
}

公共类测试
{
公共字符串A {搞定;组; }
公共字符串B {搞定;组; }
}



我觉得在我的代码上面的错字不少。我总是惊讶,编译器似乎并不关心这个。为什么上面没有一个语法errror?是否有任何实际有效的使用?


解决方案

我发现上面的错字在我的代码相当很多。我总是惊讶,编译器似乎并不关心这个。为什么上面没有一个语法errror?




由于人们在设计C#语法文法足够聪明去学习其他的编程经验教训其中的的语言中没有的允许晃来晃去逗号,在这些语言的编程人员的不断刺激。



例如,ECMAScript的(JavaScript的)是沉默在这个问题上开始,所以自然有些实现(SpiderMonkey的在Firefox,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.

这篇关于内联财产初始化和尾随逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆