This one has always puzzled me, but i'm guessing there is a very sensible explanation of why it开发者_JS百科 happens.
When you have a collection initializer the compiler allows a trailing comma, e.g.
new Dictionary<string, string>
{
{ "Foo", "Bar "},
};
and
new List<string>
{
"Foo",
};
Anyone know why this trailing comma is allowed by the compiler?
Probably mainly for tools like code generators, where is it hugely convenient not to have to know if this is the first or last item. Arguably this shouldn't be a determining factor, but (having written such tools) I am grateful for it.
Similar reason to .NET Enumeration allows comma in the last field
It's a programmer convenience since the developer can simply copy and paste the last line to extend the list. C#/.NET is good like this :)
I am guessing for two reasons:
- It would have been extra work to have the compiler recognise and treat the last line differently to the others.
- It is actually handy to have the trailing comma as it allow lines to be arranged without causing unnecessary build failures.
When you change this:
new List<string>
{
"Foo",
};
to that:
new List<string>
{
"Foo",
"Bar",
};
Diff-Tools will only highlight the added line. So e.g. during code review, you only have to check the new line.
精彩评论