Object and Collection Initializers



Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type. Note the use of auto-implemented properties in the Test class.

private class Cat { // Auto-implemented properties public int Age { get; set; } public string Name { get; set; } } static void MethodA() { // Object initializer Cat cat = new Cat { Age = 10, Name = "Sylvester" }; }

Object Initializers with anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized with an object initializer. In the select clause, a query expression can transform objects of the original sequence into objects whose value and shape may differ from the original. This is very useful if you want to store only a part of the information in each object in a sequence. In the following example, assume that a product object (p) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the product name and the unit price.

var productInfos = from p in products select new { p.ProductName, p.UnitPrice };

When this query is executed, the productInfos variable will contain a sequence of objects that can be accessed in a foreach statement as shown in this example:

foreach(var p in productInfos){...}

Each object in the new anonymous type has two public properties which receive the same names as the properties or fields in the original object. You can also rename a field when you are creating an anonymous type; the following example renames the UnitPrice field to Price.

select new {p.ProductName, Price = p.UnitPrice};

Инициализаторы объектов и коллекций

Инициализаторы объектов позволяют присваивать значения всем доступным полям и свойствам объекта в момент создания без явного вызова конструктора. В следующем примере показано, как использовать инициализатор с именованным типом. Обратите внимание на использование в классе Test автоматически реализуемых свойств. Дополнительные сведения см. в разделе Автоматически реализуемые свойства.

ß---

Инициализаторы объектов и анонимные типы[37]

Хотя инициализаторы объектов можно использовать практически в любой ситуации, особенно полезными они бывают в выражениях запросов LINQ. В выражениях запросов часто используются анонимные типы, которые можно инициилизировать только с помощью инициализаторов объектов. В инструкции select выражение запроса может преобразовывать исходную последовательность в объекты, значение и тип которых могут отличаться от оригинала. Это бывает полезно, если требуется сохранить лишь часть содержащейся в последовательности информации. В приведенном ниже примере предполагается, что у объекта продукта (p) имеется множество полей и методов, и требуется создать последовательность объектов, содержащую только имя продукта и его цену.

var productInfos = from p in products select new { p.ProductName, p.UnitPrice };

При выполнении этого запроса в переменной productInfos будет содержаться последовательность объектов, доступных в инструкции foreach, как показано в следующем примере.

foreach(var p in productInfos){...}

У каждого из объектов нового анонимного типа имеется два общедоступных свойства, имеющих те же имена, что и у соответствующих свойств или полей исходного объекта. Кроме того, при создании анонимного типа можно переименовать поле; в следующем примере выполняется переименование поля UnitPrice в Price.

select new {p.ProductName, Price = p.UnitPrice};

Object initializers with nullable types

It is a compile-time error to use a collection initializer with a nullable struct.

Collection Initializers

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

The following examples shows two simple collection initializers:

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };

The following collection initializer uses object initializers to initialize objects of the Cat class defined in an earlier example. Note that the individual object initializers are enclosed in braces and separated by commas.

List<Cat> cats = new List<Cat> { new Cat(){ Name="Sylvester", Age=8 }, new Cat(){ Name="Whiskers", Age=2}, new Cat() { Name="Sasha", Age=14} };

You can specify null as an element in a collection initializer if the collection's Add method allows it.

List<Cat> moreCats = new List<Cat> { new Cat(){ Name="Furrytail", Age=5 }, new Cat(){ Name="Peaches", Age=4}, null };

 


Дата добавления: 2019-03-09; просмотров: 205; Мы поможем в написании вашей работы!

Поделиться с друзьями:






Мы поможем в написании ваших работ!