Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Автоматически реализуемые свойства

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

Пример

В следующем примере показан простой класс, имеющий несколько автоматически реализованных свойств.

class LightweightCustomer

{

public double TotalPurchases { get; set; }

public string Name { get; private set; } // read-only

public int CustomerID { get; private set; } // read-only

}

Автоматически реализуемые свойства должны объявлять оба метода доступа — get и set. Чтобы создать автоматически реализуемое свойство readonly, задайте ему закрытый метод доступа set.

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

How to: Implement a Lightweight Class with Auto-Implemented Properties

This example shows how to create a lightweight class that serves only to encapsulate a set of auto-implemented properties. Use this kind of construct instead of a struct when you must use reference type semantics.

Example

public class Contact

{

public string Name { get; set; }

public string Address { get; set; }

public int ContactNumber { get; set; }

public int ID { get; private set; } // readonly

}

The compiler creates backing fields for each auto-implemented property. The fields are not accessible directly from source code.

Реализация облегченного класса с автоматически реализуемыми свойствами

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

Пример

public class Contact

{

public string Name { get; set; }

public string Address { get; set; }

public int ContactNumber { get; set; }

public int ID { get; private set; } // readonly

}

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

Indexers

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.

class SampleCollection<T>

{

private T[] arr = new T[100];

public T this[int i]

{

get

{

return arr[i];

}

set

{

arr[i] = value;

}

}

}

// This class shows how client code uses the indexer

class Program

{

static void Main(string[] args)

{

SampleCollection<string> stringCollection = new SampleCollection<string>();

stringCollection[0] = "Hello, World";

System.Console.WriteLine(stringCollection[0]);

}

}

Indexers Overview

  • Indexers enable objects to be indexed in a similar manner to arrays.

  • A get accessor returns a value. A set accessor assigns a value.

  • The this keyword is used to define the indexers.

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

  • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  • Indexers can be overloaded.

  • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.