Syntax of anonymous type without explicit keys (`new { identifier }`)?

∥☆過路亽.° 提交于 2019-12-10 17:34:13

问题


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.


回答1:


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.




回答2:


Not sure about C#-3.0, but the C#-4.0 reference talks about this in section 7.6.10.6 Anonymous object creation expressions.

An anonymous object initializer declares an anonymous type and returns an instance of that type. An anonymous type is a nameless class type that inherits directly from object. The members of an anonymous type are a sequence of read-only properties inferred from the anonymous object initializer used to create an instance of the type.

I've seen anonymous types used extensively in ASP.Net MVC for things like passing arbitrary HTML attributes to an Html Helper method.



来源:https://stackoverflow.com/questions/5400212/syntax-of-anonymous-type-without-explicit-keys-new-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!