logo search
CSharp_Prog_Guide

Определение различия между передачей структуры и ссылки класса в метод

В этом примере показывается, что при передаче структуры в метод передается копия структуры, а при передаче экземпляра класса передается ссылка.

В результате выполнения следующего примера видно, что при передаче экземпляра класса в метод ClassTaker изменяется только значение в поле класса. Однако при передаче экземпляра структуры в метод StructTaker ее поле не изменяется. Это происходит потому, что в метод StructTaker передается копия структуры, а в метод ClassTaker передается ссылка на класс.

Пример

----

Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.

var v = new { Amount = 108, Message = "Hello" };

Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.

Anonymous types are created by using the new operator with an object initializer.

Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed.

The most common scenario is to initialize an anonymous type with some properties from another type. In the following example, assume a class that is named Product that includes Color and Price properties together with several other properties that you are not interested in. Products is a collection of Product objects. The anonymous type declaration starts with the new keyword. It initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.

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. You must provide a name to a property that is being initialized with an expression.