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

Structs

A struct in C# is similar to a class, but structs lack certain features, such as inheritance. Also, since a struct is a value type, it can typically be created faster than a class. If you have tight loops in which new data structures are being created in large numbers, you should consider using a struct instead of a class. Structs are also used to encapsulate groups of data fields such as the coordinates of a point on a grid, or the dimensions of a rectangle.

Example

This example program defines a struct to store a geographic location. It also overrides the ToString() method to produce a more useful output when displayed in the WriteLine statement. As there are no methods in the struct, there is no advantage in defining it as a class.

struct GeographicLocation

{

private double longitude;

private double latitude;

public GeographicLocation(double longitude, double latitude)

{

this.longitude = longitude;

this.latitude = latitude;

}

public override string ToString()

{

return System.String.Format("Longitude: {0} degrees, Latitude: {1} degrees", longitude, latitude);

}

}

class Program

{

static void Main()

{

GeographicLocation Seattle = new GeographicLocation(123, 47);

System.Console.WriteLine("Position: {0}", Seattle.ToString());

}

}

Output

The output from this example looks like this:

Position: Longitude: 123 degrees, Latitude: 47 degrees

Структуры

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

Пример

В следующем примере программы определяется struct для сохранения географического расположения. Здесь также переопределяется метод ToString() для вывода более необходимых результатов при отображении в операторе WriteLine. Поскольку в struct методы отсутствуют, определение структуры в качестве класса бессмысленно.39

-----

Результат

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

Position: Longitude: 123 degrees, Latitude: 47 degrees

Variables and Constants

A variable represents a numeric or string value or an object of a class. The value that the variable stores may change, but the name stays the same. A variable is one type of field. The following code is a simple example of how to declare an integer variable, assign it a value, and then assign it a new value.

int x = 1; // x holds the value 1

x = 2; // now x holds the value 2

In C#, variables are declared with a specific data type and a label. If your programming background is in loosely typed languages such as JScript, you are used to using the same "var" type for all variables, but in C# you must specify whether your variable is an int, a float, a byte, a short, or any of the more than 20 different data types. The type specifies, among other things, the exact amount of memory that must be allocated to store the value when the application runs. The C# language enforces certain rules when converting a variable from one type to another.

int answer = 42;

string greeting = "Hello, World!";

double bigNumber = 1e100;

System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber);

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