How to: Know the Difference Between Passing a Struct and Passing a Class Reference to a Method 


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



ЗНАЕТЕ ЛИ ВЫ?

How to: Know the Difference Between Passing a Struct and Passing a Class Reference to a Method



This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

The output of the following example shows that only the value of the class field is changed when the class instance is passed to the ClassTaker method. The struct field, however, does not change by passing its instance to the StructTaker method. This is because a copy of the struct is passed to the StructTaker method, while a reference to the class is passed to the ClassTaker method.

Example

class TheClass { public string willIChange; } struct TheStruct { public string willIChange; } class TestClassAndStruct { static void ClassTaker(TheClass c) { c.willIChange = "Changed"; } static void StructTaker(TheStruct s) { s.willIChange = "Changed"; } static void Main() { TheClass testClass = new TheClass(); TheStruct testStruct = new TheStruct(); testClass.willIChange = "Not Changed"; testStruct.willIChange = "Not Changed"; ClassTaker(testClass); StructTaker(testStruct); System.Console.WriteLine("Class field = {0}", testClass.willIChange); System.Console.WriteLine("Struct field = {0}", testStruct.willIChange); } }
Class field = Changed Struct field = Not Changed

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

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

В результате выполнения следующего примера видно, что при передаче экземпляра класса в метод 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.

 


Анонимные типы

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

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

Анонимные типы обычно используются в предложении select выражения запроса для возврата подмножества свойств из каждого объекта в исходной последовательности.

Анонимные типы создаются при помощи оператора new с инициализатором объекта. Дополнительные сведения об инициализаторах объектов см. в разделе Инициализаторы объектов и коллекций.

Анонимные типы — это типы class, состоящие из одного или более открытых свойств только для чтения. Все остальные виды членов класса, такие как методы или события, запрещены.

Обычно анонимный тип инициализируется определенными свойствами другого типа. В приведенном ниже примере используется класс Product, включающий свойства Color и Price, а также несколько других свойств, которые нас не интересуют. Products — это коллекция объектов Product. Анонимные объявления типа начинаются с ключевого слова new. Оно инициализирует новый тип, который использует только два свойства из класса Product. Это приводит к уменьшению объема возвращаемых данных.

Если не указать имена членов в анонимном типе, компилятор присвоит этим членам имя свойства, которое используется для их инициализации. Для свойства, которое инициализируется выражением, необходимо указывать имя.

 


 

var productQuery = from prod in products select new { prod.Color, prod.Price }; foreach (var v in productQuery) { Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price); }

When an anonymous type is assigned to a variable, that variable must be initialized with the var construct. This is because only the compiler has access to the underlying name of the anonymous type.

Remarks

Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.

An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Anonymous types cannot contain unsafe types as properties.

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

 


 

ß----

Если переменной назначается анонимный тип, эта переменная должна инициализироваться конструкцией var. Это объясняется тем, что доступ к базовому имени анонимного типа имеет только компилятор. Дополнительные сведения о var см. в разделе Неявно типизированные локальные переменные.

Заметки

Анонимные типы являются ссылочными типами, которые происходят непосредственно от объекта. Компилятор присваивает им имена, несмотря на то что они недоступны для вашего приложения. С точки зрения среды CLR анонимный тип ничем не отличается от любого другого ссылочного типа.

Если два или более анонимных типа имеют одинаковые номера и типы свойств одного порядка, компилятор обрабатывает их как один и тот же тип, в результате чего им присваивается одна и та же информация о типе, созданная компилятором.

Анонимный тип имеет область действия метода. Для передачи анонимного типа или коллекции анонимных типов за границы метода необходимо прежде всего привести тип к объекту. Однако это нарушает строгое определение анонимного типа. Если результаты запроса нужно сохранить или передать за границы метода, попробуйте воспользоваться обычной именованной структурой или классом вместо анонимного типа.

Анонимные типы не могут содержать небезопасные типы в качестве свойств.

Поскольку методы Equals и GetHashCode анонимных типов определены через Equals и GetHashcode свойств, два экземпляра одного анонимного типа будут идентичны только тогда, когда идентичны все их свойства.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 77; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.141.41.187 (0.006 с.)