在匿名内部声明 属性 的第三种语法是什么?
What is a third syntax for declaring a property inside an anonymous?
在匿名中声明 属性 的第三种语法是什么?
我正在阅读 CLR via C# 一书。我看到了以下摘录 (1):
The compiler supports two additional syntaxes for declaring a property inside an anonymous type
where it can infer the property names and types from variables:
String Name = "Grant";
DateTime dt = DateTime.Now;
// Anonymous type with two properties
// 1. String Name property set to Grant
// 2. Int32 Year property set to the year inside the dt
var o2 = new { Name, dt.Year };
虽然前面几段作者介绍了以下用于创建匿名类型的语法 (2):
// Define a type, construct an instance of it, & initialize its properties
var o1 = new { Name = "Jeff", Year = 1964 };
因此,从上面的两个摘录中我得出结论,有一种语法用于在匿名类型中声明 属性 和另外两种语法。虽然书中介绍了一种附加语法,但我仍然没有看到书中介绍了第二种附加语法。
我听说过语法和第一个附加语法,并且在我的应用程序中有几次使用它们。但我不记得使用任何其他语法(这将是第三种)。
所有这一切让我相信实际上只有两种语法,而第三种(这是第二个额外的)不存在。上面的摘录只是书中的一个错误:作者应该写
... supports two additional ...
此外,我在互联网上找不到关于第三种语法的任何内容。
所以,这只是一个错误还是我错过了这里的第三个语法?
You create anonymous types by using the new operator together with an object initializer.
描述了对象初始化语法 here。是这样的语法:
{ PropertyName = value, ... }
回到匿名类型文档:
If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.
所以,只有一种语法:
new {[PropertyName =] value, ...}
如果值为 属性,则 PropertyName =
部分是可选的。 (字段呢?)。
正如评论中所说,您的消息来源措辞不当。
在匿名中声明 属性 的第三种语法是什么?
我正在阅读 CLR via C# 一书。我看到了以下摘录 (1):
The compiler supports two additional syntaxes for declaring a property inside an anonymous type where it can infer the property names and types from variables:
String Name = "Grant";
DateTime dt = DateTime.Now;
// Anonymous type with two properties
// 1. String Name property set to Grant
// 2. Int32 Year property set to the year inside the dt
var o2 = new { Name, dt.Year };
虽然前面几段作者介绍了以下用于创建匿名类型的语法 (2):
// Define a type, construct an instance of it, & initialize its properties
var o1 = new { Name = "Jeff", Year = 1964 };
因此,从上面的两个摘录中我得出结论,有一种语法用于在匿名类型中声明 属性 和另外两种语法。虽然书中介绍了一种附加语法,但我仍然没有看到书中介绍了第二种附加语法。
我听说过语法和第一个附加语法,并且在我的应用程序中有几次使用它们。但我不记得使用任何其他语法(这将是第三种)。
所有这一切让我相信实际上只有两种语法,而第三种(这是第二个额外的)不存在。上面的摘录只是书中的一个错误:作者应该写
... supports
twoadditional ...
此外,我在互联网上找不到关于第三种语法的任何内容。
所以,这只是一个错误还是我错过了这里的第三个语法?
You create anonymous types by using the new operator together with an object initializer.
描述了对象初始化语法 here。是这样的语法:
{ PropertyName = value, ... }
回到匿名类型文档:
If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.
所以,只有一种语法:
new {[PropertyName =] value, ...}
如果值为 属性,则 PropertyName =
部分是可选的。 (字段呢?)。
正如评论中所说,您的消息来源措辞不当。