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

Пример результатов выполнения

Execution Succeded

return value = 0

Types

C# is a strongly typed language; therefore every variable and object must have a declared type.

Data Types Overview

A type can be described as being either:

  • A built-in numeric type, such as an int or char, or

  • A user-defined type, such as a class or interface.

  • An anonymous type, which consists of a set of public properties encapsulated in a nameless reference type.

Types can also be defined as being either:

  • Value Types (C# Reference), which store values. These include the primitive numeric types, enums and structs, and also nullable versions of these types.

  • Reference Types (C# Reference), which store references to the actual data. These include classes, interfaces, arrays and delegates.

Типы

C# — это строго типизированный язык, поэтому каждая переменная и каждый объект должны иметь объявленный тип.

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

Тип можно описать как:

  • Встроенный числовой тип, например int или char, или

  • Пользовательский тип, например class или interface.

  • Анонимный тип, состоящий из набора общих свойств, инкапсулированных в безымянном ссылочном типе.

Типы также могут быть заданы как:

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

  • Ссылочные типы, то есть хранящие ссылки на фактические данные. К ним относятся классы, интерфейсы, массивы и делегаты.

Casting

Converting between data types can be done explicitly by using a cast, but in some cases, implicit conversions are allowed. For example:

static void TestCasting()

{

int i = 10;

float f = 0;

f = i; // An implicit conversion, no data will be lost.

f = 0.5F;

i = (int)f; // An explicit conversion. Information will be lost.

}

A cast explicitly invokes the conversion operator from one type to another. The cast fail if no such conversion operator is defined. A cast operation between reference types does not change the type of the underlying object; it only changes the type of the variable that is being used as a reference to that object.

You can write custom conversion operators to convert between user-defined types.

Example

The following program casts a double to an int. The program will not compile without the cast.

class Test

{

static void Main()

{

double x = 1234.7;

int a;

a = (int)x; // cast double to int

System.Console.WriteLine(a);

}

}

Output

1234

Приведение

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

static void TestCasting()

{

int i = 10;

float f = 0;

f = i; // An implicit conversion, no data will be lost.

f = 0.5F;

i = (int)f; // An explicit conversion. Information will be lost.

}

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

Пример

Следующая программа выполнят приведение типа double к типу int. Без приведения эта программа скомпилирована не будет.

class Test

{

static void Main()

{

double x = 1234.7;

int a;

a = (int)x; // cast double to int

System.Console.WriteLine(a);

}

}