X# 为语言添加了两种初始化器:集合初始化器和对象初始化器。其语法如下
constructorcall : datatype { parameterlist? } initializer?
;
initializer : objectinitializer
| collectioninitializer
;
objectinitializer : { (memberinitializer (, memberinitializer)*)? }
;
memberinitializer : Name=identifierName := Expr=initializervalue
;
initializervalue : objectOrCollectioninitializer
| expression
;
collectioninitializer : { expression (, expression)* }
;
•初始化器也用大括号分隔,紧跟在构造函数调用的结尾大括号之后
对象初始化器的示例
VAR oPerson := Person{}{FirstName := "John", LastName := "Smith"}
VAR oPerson := Person{"John", "Smith"} {Age := 35 }
集合初始化器示例
oList := List<Int>{} {1,2,3,4,5}
结合在一起:
Var oPeople := List<Person> {} {;
Person{}{FirstName := "John", LastName := "Smith"}, ;
Person{}{FirstName := "Jane", LastName := "Doe"} ;
}
LINQ 示例 展示了不同初始化器的运行情况。