Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp Language Specification.doc
Скачиваний:
12
Добавлен:
26.09.2019
Размер:
4.75 Mб
Скачать

11.3.9Деструкторы

В структуре не разрешается объявлять деструктор.

11.3.10Статические конструкторы

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

  • Ссылка на статический член с типом структуры.

  • Вызов явным образом объявленного конструктора с типом структуры.

Создание значений по умолчанию (§11.3.4) с типом структуры не ведет к вызову статического конструктора. В качестве примера можно указать начальные значения элементов массива.

11.4Примеры структур

Ниже приводится два примера использования типов struct для создания типов, которые могут использоваться аналогично встроенным типам языка, но имеют измененную семантику.

11.4.1Тип целочисленного значения в базе данных

Представленная ниже структура DBInt реализует тип integer, который может представлять полный набор значений с типом int, а также дополнительное состояние, указывающее на неизвестное значение. Тип с такими характеристиками повсеместно используется в базах данных.

using System;

public struct DBInt { // The Null member represents an unknown DBInt value.

public static readonly DBInt Null = new DBInt();

// When the defined field is true, this DBInt represents a known value // which is stored in the value field. When the defined field is false, // this DBInt represents an unknown value, and the value field is 0.

int value; bool defined;

// Private instance constructor. Creates a DBInt with a known value.

DBInt(int value) { this.value = value; this.defined = true; }

// The IsNull property is true if this DBInt represents an unknown value.

public bool IsNull { get { return !defined; } }

// The Value property is the known value of this DBInt, or 0 if this // DBInt represents an unknown value.

public int Value { get { return value; } }

// Implicit conversion from int to DBInt.

public static implicit operator DBInt(int x) { return new DBInt(x); }

// Explicit conversion from DBInt to int. Throws an exception if the // given DBInt represents an unknown value.

public static explicit operator int(DBInt x) { if (!x.defined) throw new InvalidOperationException(); return x.value; }

public static DBInt operator +(DBInt x) { return x; }

public static DBInt operator -(DBInt x) { return x.defined ? -x.value : Null; }

public static DBInt operator +(DBInt x, DBInt y) { return x.defined && y.defined? x.value + y.value: Null; }

public static DBInt operator -(DBInt x, DBInt y) { return x.defined && y.defined? x.value - y.value: Null; }

public static DBInt operator *(DBInt x, DBInt y) { return x.defined && y.defined? x.value * y.value: Null; }

public static DBInt operator /(DBInt x, DBInt y) { return x.defined && y.defined? x.value / y.value: Null; }

public static DBInt operator %(DBInt x, DBInt y) { return x.defined && y.defined? x.value % y.value: Null; }

public static DBBool operator ==(DBInt x, DBInt y) { return x.defined && y.defined? x.value == y.value: DBBool.Null; }

public static DBBool operator !=(DBInt x, DBInt y) { return x.defined && y.defined? x.value != y.value: DBBool.Null; }

public static DBBool operator >(DBInt x, DBInt y) { return x.defined && y.defined? x.value > y.value: DBBool.Null; }

public static DBBool operator <(DBInt x, DBInt y) { return x.defined && y.defined? x.value < y.value: DBBool.Null; }

public static DBBool operator >=(DBInt x, DBInt y) { return x.defined && y.defined? x.value >= y.value: DBBool.Null; }

public static DBBool operator <=(DBInt x, DBInt y) { return x.defined && y.defined? x.value <= y.value: DBBool.Null; }

public override bool Equals(object obj) { if (!(obj is DBInt)) return false; DBInt x = (DBInt)obj; return value == x.value && defined == x.defined; }

public override int GetHashCode() { return value; }

public override string ToString() { return defined? value.ToString(): “DBInt.Null”; } }

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]