为什么C#会在集合初始值设定项中允许尾随逗号,但在params中却不允许尾随逗号? [英] Why does C# allow trailing comma in collection initializers but not in params?

查看:64
本文介绍了为什么C#会在集合初始值设定项中允许尾随逗号,但在params中却不允许尾随逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有效语法:

var test = new List<string>
{
   "a",
   "b",
   "c",//Valid trailing comma
};

无效的语法:

private void Test(params string[] args)
{
}

Test(
   "a",
   "b",
   "c",//Invalid trailing comma
);

是语法不一致还是决定性的决定?

Is it a matter of syntax inconsistency or a calculated decision?

推荐答案

因此,即使我永远都不知道真正的"原因(因为我不在编译器团队中),我还是会对此采取行动-以及可能性一个人出现是有问题的.

So I'll take a stab at this even though I will never know the "true" reason as I wasn't on the compiler team - and the likelihood of one turning up is questionable.

尾随逗号通常在某些情况下很有用,即合并和代码生成.在诸如集合或属性初始化器和枚举之类的东西的上下文中,用逗号结尾是无害的(编译器可以安全地推断列表结尾",因为它也可以使用一个封闭的括号括起来.

Trailing commas are generally useful in a few scenarios, namely merging and code-generation. In the context of stuff like collection or property initialisers and enums, leaving a trailing comma is harmless (the compiler can safely infer "end of list" as there is also a closing block bracket it can hook on to.

方法参数非常明确-编译器在此区域需要大量控制,以便在人们进行编码或其他辅助功能时提供良好的反馈.在方法参数上留下逗号不会添加上述任何值,并且我开始引起如何处理不完整"代码的困惑(用户是否故意将其保留在此处,或者它们只是要键入下一个参数)?).

Method parameters are quite explicit - the compiler needs a lot of control in this area so that it can provide good feedback when people are coding and for other ancillary features. Leaving a trailing comma on method arguments doesn't add any of the value as above and my start to cause confusion over how to handle "incomplete" code (did the user leave it there intentionally or are they just about to type in the next argument?).

您正确地认为 params 落入了 conceptual 的空白,因为您将它们视为数组,并且可以将其指定为逗号分隔(在集合初始化程序).那么,为什么它们在风格上与集合初始化方法有所不同?

You are correct that params fall into the conceptual gap in that you see them as an array, and you can specify them as comma delimited (which was supported prior to collection initialisers). So why do they depart in style from collection initialisers?

params 位的语言规范没有明确指定尾部逗号支持,尽管它确实是针对与其他语言(C ++)同等的集合初始化器,但它确实增加了对迁移到的开发人员的熟悉度来自其他地方的C#.

The language spec for the params bit doesn't explicitly specify trailing comma support, though it does for collection initialisers for parity towards other languages (C++ I think), which increases familiarity with developers migrating to C# from elsewhere.

我的假设:事实并非如此,这导致 YAGNI 适用,并且从这一点出发,该功能的价值主张是毋庸置疑的,它支持不实施它.

My supposition: the fact that it wasn't in spec then causes YAGNI to apply, and from that point forwards the value proposition for the feature is a no-brainer in favour of not implementing it.

这篇关于为什么C#会在集合初始值设定项中允许尾随逗号,但在params中却不允许尾随逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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