Implicitly Typed Local Variables 


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



ЗНАЕТЕ ЛИ ВЫ?

Implicitly Typed Local Variables



Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, a type defined in the.NET Framework class library, or any expression.

The following examples show various ways in which local variables can be declared with var:

// i is compiled as an int var i = 5; // s is compiled as a string var s = "Hello"; // a is compiled as int[] var a = new[] { 0, 1, 2 }; // expr is compiled as IEnumerable<Customer> var expr = from c in customers where c.City == "London" select c; // anon is compiled as an anonymous type var anon = new { Name = "Terry", Age = 34 }; // list is compiled as List<int> var list = new List<int>();

It is important to understand that the var keyword does not mean “Variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

The var keyword may be used in the following contexts:

· On local variables (variables declared at method scope) as shown in the previous example.

· In a for initialization statement.

for(var x = 1; x < 10; x++)

· In a foreach initialization statement.

foreach(var item in list){...}

· In a using Statement

using (var file = new StreamReader("C:\\myfile.txt")) {...}

Неявно типизированные локальные переменные

Локальным переменным вместо явного типа может быть задан определенный "тип" var. Ключевое слово var сообщает компилятору необходимости определения типа переменной из выражения, находящегося с правой стороны оператора инициализации. Определенный тип может быть встроенным, анонимным, определенным пользователем типом, типом, определенным в библиотеке классов, или любым выражением. Дополнительные сведения об инициализации массивов с var см. в разделе Неявно типизированные массивы.

В следующем примере показаны разные способы объявления локальных переменных с var.

ß---

 

 

Важно понять, что ключевое слово var не означает "вариант" и не указывает на свободную типизацию или позднюю привязку переменной. Оно просто значит, что компилятор определяет и назначает наиболее подходящий тип.

Ключевое слово var можно использовать в следующих контекстах:

· в локальных переменных (переменных, объявленных в области действия метода), как показано в предыдущем примере;

· в операторе инициализации for;

for(var x = 1; x < 10; x++)

· в операторе инициализации for;

foreach(var item in list){...}

· в операторе операторе using.

using (var file = new StreamReader("C:\\myfile.txt")) {...}

Var and Anonymous Types

In many cases the use of var is optional and is just a syntactic convenience. However, it is required when a variable is initialized with an anonymous type. This is a common scenario in LINQ query expressions.

Because the name of an anonymous type is known only to the compiler, you must use var in your source code. If a query variable has been initialized with var, then you must also use var as the type of the iteration variable in the foreach statement that iterates over the query variable.

class ImplicitlyTypedLocals2 { static void Main() { string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };   // If a query produces a sequence of anonymous types, // then you must also use var in the foreach statement. var upperLowerWords = from w in words select new { Upper = w.ToUpper(), Lower = w.ToLower() };   // Execute the query foreach (var ul in upperLowerWords) { Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); } } } /* Outputs: Uppercase: APPLE, Lowercase: apple Uppercase: BLUEBERRY, Lowercase: blueberry Uppercase: CHERRY, Lowercase: cherry */

 


Var и анонимные типы

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

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

ß-----


Remarks

The following restrictions apply to implicitly-typed variable declarations:

· var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null.

· var cannot be used on fields at class scope.

· Variables declared by using var cannot be used in the initialization expression. In other words, var v = v++; produces a compile-time error.

· Multiple implicitly-typed variables cannot be initialized in the same statement.

· If a type named var is in scope, then you will get a compile-time error if you try to initialize a local variable with the var keyword.

The only scenario in which a local variable must be implicitly typed with var is in the initialization of anonymous types.

You may find that var can also be useful with query expressions in which the exact constructed type of the query variable is difficult to determine. This can occur with grouping and ordering operations.

The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IEnumerable<Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

// Same as previous example except we use the entire last name as a key. // Query variable is an IEnumerable<IGrouping<string, Student>> var studentQuery3 = from student in students group student by student.Last;

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.


Заметки

К объявлениям неявно типизированных переменных применимы следующие ограничения.

· var может использоваться, только если локальная переменная объявлена и инициализирована в одном операторе; переменная не может быть инициализирована значением NULL.

· var не может использоваться в полях в области действия класса.

· Переменные, объявленные с помощью var, не могут использоваться в выражении инициализации. Другими словами, var v = v++; вызывает ошибку времени компиляции.

· В одном операторе нельзя инициализировать несколько неявно типизированных переменных.

· Если тип с именем var находится в области действия, при попытке инициализировать локальную переменную с var возникнет ошибка времени компилятора.

Инициализация анонимного типа является единственным сценарием, когда локальная переменная должна быть явно типизирована с var. Дополнительные сведения см. в разделе Анонимные типы.

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

Ключевое слово var удобно, когда определенный тип переменной сложно вводить с клавиатуры, либо он является очевидным, либо не повышает удобочитаемость кода. Примером подобного применения ключевого слова var служит ситуация со вложенными универсальными типами, которые используются операциях по группировке. В следующем запросе используется переменная запроса с типом IEnumerable<IEnumerable<Student>>. При условии, что пользователи, работающие с кодом, понимают данные принципы, не возникнет никаких проблем с использованием неявной типизации для удобства и краткости.

ß----

Однако использование ключевого слова var может сделать код более трудным для понимания другими разработчиками. По этой причине в документации по C# ключевое слово var обычно используется только при необходимости.

 


Properties

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod { private double seconds;   public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } } }   class Program { static void Main() { TimePeriod t = new TimePeriod();   // Assigning the Hours property causes the 'set' accessor to be called. t.Hours = 24;   // Evaluating the Hours property causes the 'get' accessor to be called. System.Console.WriteLine("Time in hours: " + t.Hours); } }

Свойства

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

В данном пример класс TimePeriod хранит сведения о периоде времени. Внутри класса время хранится в секундах, но свойство с именем Hours позволяет клиенту задать время в часах. Методы доступа для свойства Hours выполняют преобразование между часами и секундами.

Пример

ß----


Output

Time in hours: 24

Properties Overview

· Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

· A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

· The value keyword is used to define the value being assigned by the set indexer.

· Properties that do not implement a set method are read only.

· For simple properties that require no custom accessor code, consider the option of using auto-implemented properties.

 


Результат

Time in hours: 24

Общие сведения о свойствах

· Свойства позволяют классу предоставлять общий способ получения и задания значений, скрывая при этом код реализации или проверки.

· Метод доступа свойства get используется для возврата значения свойства, а метод доступа set используется для назначения нового значения. Эти методы доступа могут иметь различные уровни доступа. Дополнительные сведения см. в разделе Асимметричные методы доступа.

· Ключевое слово value используется для определения значения, присваиваемого индексатором set.

· Свойства, которые не реализуют метод set, доступны только для чтения.

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

 


Using Properties

Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field, accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor. The code block for the get accessor is executed when the property is read; the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write.

Unlike fields, properties are not classified as variables. Therefore, you cannot pass a property as a ref or out parameter.

Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields.

Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get -accessor and/or a set accessor. For example:

public class Date { private int month = 7; //"backing store"   public int Month { get { return month; } set { if ((value > 0) && (value < 13)) { month = value; } } } }

Использование свойств

Свойства объединяют функции полей и методов. Для объекта, использующего какой-либо объект, свойство является полем, поэтому для доступа к свойству требуется тот же синтаксис, что и для поля. Для средства реализации класса свойство является одним или двумя блоками кода, представляющими метод доступа get и/или метод доступа set. Блок кода для метода доступа get выполняется, когда осуществляется чтение свойства; блок кода для метода доступа set выполняется, когда свойству присваивается новое значение. Свойство без метода доступа set считается доступным только для чтения. Свойство без метода доступа get считается доступным только для чтения. Свойство с обоими методами доступа доступно для чтения и для записи.

В отличие от полей свойства не классифицируются как переменные. Поэтому свойство нельзя передать в качестве параметра ref или out.

Свойства имеют множество применений: с их помощью можно проверить данные перед разрешением изменения, они могут прозрачно представлять данные в классе, куда эти данные извлекаются из какого-либо другого источника, например базы данных, они могут выполнять действие при изменении данных, например вызов события или изменение значения в других полях.

Свойства объявляются в блоке класса с помощью последовательного указания уровня доступа для поля, типа свойства, имени свойства и блока кода, в котором объявляется метод доступа get и/или set. Пример.

ß-----


In this example, Month is declared as a property so that the set accessor can make sure that the Month value is set between 1 and 12. The Month property uses a private field to track the actual value. The real location of a property's data is often referred to as the property's "backing store." It is common for properties to use private fields as a backing store. The field is marked private in order to make sure that it can only be changed by calling the property.

Auto-implemented properties provide simplified syntax for simple property declarations.

The get Accessor

The body of the get accessor resembles that of a method. It must return a value of the property type. The execution of the get accessor is equivalent to reading the value of the field. For example, when you are returning the private variable from the get accessor and optimizations are enabled, the call to the get accessor method is inlined by the compiler so there is no method-call overhead. However, a virtual get accessor method cannot be inlined because the compiler does not know at compile-time which method may actually be called at run time. The following is a get accessor that returns the value of a private field name:

class Person { private string name; // the name field public string Name // the Name property { get { return name; } } }

When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. For example:

Person p1 = new Person(); //... System.Console.Write(p1.Name); // the get accessor is invoked here

 


В данном примере Month объявляется как свойство, поэтому метод доступа set может обеспечить задание для свойства Month значения от 1 до 12. Свойство Month использует частное поле для отслеживания фактического значения. Фактическое местоположение данных свойства часто называется "резервным хранилищем" этого свойства. Обычно в качестве резервного хранилища свойств используются частные поля. Поле помечается как частное для того, чтобы предотвратить изменение других полей при вызове данного свойства. Дополнительные сведения об ограничениях общего и закрытого доступа см. в разделе Модификаторы доступа.

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

Метод доступа get

Основная часть метода доступа get похожа на основную часть метода. Она должна возвращать значение типа свойства. Выполнение метода доступа get эквивалентно считыванию значения поля. Например, когда возвращается частная переменная из метода доступа get и разрешена оптимизация, вызов метода доступа get встраивается компилятором, что позволяет избежать ненужных затрат на вызов метода. Однако виртуальный метод доступа get не может быть встроен, поскольку во время компиляции у компилятора нет данных о том, какой метод может быть вызван во время выполнения. Ниже приведен метод доступа get, который возвращает значение частного поля name:

ß----

При создании ссылки на свойство, кроме случая присвоения ему значения, для чтения значения свойства вызывается метод доступа get. Пример.

Person p1 = new Person(); //...   System.Console.Write(p1.Name); // the get accessor is invoked here

 


The get accessor must end in a return or throw statement, and control cannot flow off the accessor body.

It is a bad programming style to change the state of the object by using the get accessor. For example, the following accessor produces the side effect of changing the state of the object every time that the number field is accessed.

private int number; public int Number { get { return number++; // Don't do this } }

The get accessor can be used to return the field value or to compute it and return it. For example:

class Employee { private string name; public string Name { get { return name!= null? name: "NA"; } } }

In the previous code segment, if you do not assign a value to the Name property, it will return the value NA.

 


Метод доступа get должен заканчиваться оператором return или throw, а элемент управления не должен выходить за основную часть метода доступа.

Изменение состояния объекта с помощью метода доступа get указывает на низкую квалификацию программиста. Например, следующий метод доступа имеет побочный эффект, заключающийся в изменении состояния объекта при каждой операции доступа к полю number.

private int number; public int Number { get { return number++; // Don't do this } }

Метод доступа get можно использовать для возвращения значения поля или для вычисления и возвращения этого значения. Пример.

class Employee { private string name; public string Name { get { return name!= null? name: "NA"; } } }

Если в предыдущем фрагменте кода свойству Name не назначается какое-либо значение, это свойство возвращает значение "NA".

 


The set Accessor

The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added to the Name property:

class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } }

When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. For example:

Person p1 = new Person(); p1.Name = "Joe"; // the set accessor is invoked here   System.Console.Write(p1.Name); // the get accessor is invoked here

It is an error to use the implicit parameter name, value, for a local variable declaration in a set accessor.

 


Метод доступа set

Метод доступа set похож на метод, имеющий тип возвращаемого значения void. В нем используется неявный параметр value, тип которого соответствует типу свойства. В следующем примере метод доступа set добавляется в свойство Name:

class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } }

Когда свойству присваивается значение, выполняется вызов метода доступа set с помощью аргумента, предоставляющего новое значение. Пример.

Person p1 = new Person(); p1.Name = "Joe"; // the set accessor is invoked here   System.Console.Write(p1.Name); // the get accessor is invoked here

Использование имени неявного параметра value для объявления локальной переменной в методе доступа set является ошибкой.

 


Remarks

Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected.

A property may be declared as a static property by using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists.

A property may be marked as a virtual property by using the virtual keyword. This enables derived classes to override the property behavior by using the override keyword.

A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract. This means that there is no implementation in the class, and derived classes must write their own implementation.

Note:
It is an error to use a virtual, abstract, or override modifier on an accessor of a static property.

 


Заметки

Свойства можно пометить как public, private, protected, internal или protected internal. Эти модификаторы доступа определяют порядок доступа к свойству для пользователей класса. Методы доступа get и set могут иметь различные модификаторы доступа для одного свойства. Например, метод доступа get может иметь модификатор public для разрешения доступа только для чтения из типа, а метод доступа set может иметь модификатор private или protected. Дополнительные сведения см. в разделе Модификаторы доступа.

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

Свойство можно пометить как статическое свойство при помощи ключевого слова virtual. Это позволяет производным классам переопределять поведение свойства при помощи ключевого слова override. Дополнительные сведения об этих параметрах содержатся в разделе Наследование.

Свойство, переопределяющее виртуальное свойство, может также быть sealed, что указывает на то, что для производных классов оно более не является виртуальным. И наконец, свойство можно объявить как abstract. Это означает, что в классе отсутствует реализация, поэтому производные классы должны создавать свою собственную реализацию. Дополнительные сведения об этих параметрах содержатся в разделе Абстрактные и запечатанные классы и члены классов.

Примечание.
Использование модификатора virtual, abstract или override для метода доступа свойства static является ошибкой.

 


Example 1

Description

This example demonstrates instance, static, and read-only properties. It accepts the name of the employee from the keyboard, increments NumberOfEmployees by 1, and displays the Employee name and number.

Code



Поделиться:


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

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