匿名类型没有明确键(`新的{}标识符`)的语法? [英] Syntax of anonymous type without explicit keys (`new { identifier }`)?

查看:208
本文介绍了匿名类型没有明确键(`新的{}标识符`)的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我看到一个陌生的语法匿名类型表达式:

 新{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匿名对象创建表达式




一个成员声明可以简写
到一个简单的名称(第7.5.2节) ,会员
访问(第7.5.4节)或基本访问
(§7.6.8)。这就是所谓的投影
初始化并且是简写的
声明并分配到具有相同名称的一个
属性。
具体来说,
形式的成员声明符




 标识符EXPR。标识符




完全等效于
以下,分别为:




 标识符=标识符标识= EXPR。标识符




因此,在一个凸起
初始化标识符选择
两者的值和该值是
分配的字段或
属性。直观地,一个投影
初始化项目不仅仅是一个值,
也值的名称。




(第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

A member declarator can be abbreviated to a simple name (§7.5.2), a member access (§7.5.4) or a base access (§7.6.8). This is called a projection initializer and is shorthand for a declaration of and assignment to a property with the same name. Specifically, member declarators of the forms

identifier                           expr . identifier

are precisely equivalent to the following, respectively:

identifer = identifier               identifier = expr . identifier

Thus, in a projection initializer the identifier selects both the value and the field or property to which the value is assigned. Intuitively, a projection initializer projects not just a value, but also the name of the value.

(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.

这篇关于匿名类型没有明确键(`新的{}标识符`)的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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