问题描述
新{MyObjectID = g.Key,totalSum}
起初我以为它(,totalSum}
)是一个语法错误,因为没有密钥被指定,但它编译并工作在C#3.0。我在LINQPad(2.X - > C#3)证实了这一语法:
VAR Y =:-) ;
变种Q =新的{Y = Y,Y,y.Length,};
q.Dump();
结果:
(匿名类型){
Y =:-),$ b $通过=:-),
长度= 3
}
凡在规范这个语法定义?(答案应包括适用的参考和相应的摘录。)
和,更主观的(随意不回答),这是一个好的语法/捷径省略钥匙?我没有用它,只要我不认识它,而且我不是很迷恋与语法糖。
7.6.10.6匿名对象创建表达式
(第181页)
在简单来说,这表示,如果你不提供自己的标识符,编译器将选择用于表达最后成员标识作为默认值。
至于如果它是好还是坏...好,我倒是恰恰避免这样做,以排除其他人谁不知道这个快捷键是一头雾水。
In this question I saw an anonymous type expression with an unfamiliar syntax:
new { MyObjectID = g.Key, totalSum }
At first I thought it (, totalSum }
) was a syntax error as no key is specified, but it compiles and works in C#3.0. I have verified this syntax in LINQPad (2.x -> C#3):
var y = ":-)";
var q = new { Y = y, y, y.Length, };
q.Dump();
Result:
(anon type) {
Y = ":-)",
y = ":-)",
Length = 3
}
Where in the specification is this syntax defined? (Answers should include an applicable reference and appropriate excerpt.)
And, more subjective (feel free not to answer), is it a good syntax/short-cut to omit the keys? I have not used it so far as I have not known about it, and I am not very enamored with that syntactical sugar.
7.6.10.6 Anonymous object creation expressions
identifier expr . identifier
identifer = identifier identifier = expr . identifier
(page 181)
In simple terms this says that if you don't provide an identifier yourself, the compiler will select the identifier for the "last" member of the expression as a default.
As for if it's good or bad... well, I 'd avoid doing it precisely to rule out the possibility that someone else who doesn't know this shortcut is confused.
这篇关于匿名类型没有明确键(`新的{}标识符`)的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!