3.4 初始化混合的值(Initializing Compound Values)
Lambda 表达式和扩展方法提供我们查询所需要的任何东西,只需简单将成员(members)过滤出数据序列(filter members out of sequence of values)。大多数查询表达式还能在那些成员上执行发送功能(perform projection),可以有效地将原始序列的成员(members of the original sequence)转换成(transforming)它们的值(value)和类型(type)可能与原来不同的成员。为了支持编写这种转换操作,LINQ 依赖(rely on)一种新的构造(construct)方法叫做“对象初始化表达式(object initialization expressions)”来创建新的结构型类型的实体(instances of structured types)。在本文余下的部分(the rest of),我们假设(assume)已经定义了下面的类型:
public class Person {
string name;
int age;
bool canCode;
public string Name {
get { return name; } set { name = value; }
}
public int Age {
get { return age; } set { age = value; }
}
public bool CanCode {
get { return canCode; } set { canCode = value; }
}
}
对象初始化表达式(object initialization expressions)允许我们简单地构造(construct)一个类型(type)的基于公共域和属性(public fields and properties)的值(values)。举例来说,要创建类型 Person 的一个新的值,语句可以这样写:
Person value = new Person {
Name = "Chris Smith", Age = 31, CanCode = false
};
从语义(Semantically)上说,它等价于(equivalent to)下面这段语句序列(sequence of statements):
Person value = new Person();
value.Name = "Chris Smith";
value.Age = 31;
value.CanCode = false;
对象初始化表达式(object initialization expressions)是语言级集成查询(language integrated query)的一个重要特性,因为它允许新的结构型值(structured values)的构造(construction)存在于只允许表达式(expressions)(就像 lambda 表达式和表达式树)的上下文里(in contexts)。考察下面这段查询表达式代码,它为输入序列(input sequence)的每个值都创建一个 Person 对象值:
IEnumerable<Person> expr = names.Select(s => new Person {
Name = s, Age = 21, CanCode = s.Length == 5
});
对象初始化语法(object initialization syntax)也是为了便于(convenient for)初始化结构型值的数组(arrays of structured values)。例于,下面的数组变量(array variable)是用单独的(individual)对象初始化(object initializers)初始化的:
static Person[] people = {
new Person { Name="Allen Frances", Age=11, CanCode=false },
new Person { Name="Burke Madison", Age=50, CanCode=true },
new Person { Name="Connor Morgan", Age=59, CanCode=false },
new Person { Name="David Charles", Age=33, CanCode=true },
new Person { Name="Everett Frank", Age=16, CanCode=true },
};
待续, 错误难免,请批评指正,译者Naven 2005-10-23