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

Static vs. Instance Members

A static member is a method or field that can be accessed without reference to a particular instance of a class. The most common static method is Main, which is the entry point for all C# programs; note that you do not need to create an instance of the containing class in order to call the Main method. Another commonly used static method is WriteLine in the Console class. Note the difference in syntax when accessing static methods; you use the class name, not the instance name, on the left side of the dot operator: Console.WriteLine.

When you declare a class field static, all instances of that class will "share" that field. If size in the following code example were declared static, and one Animal object changed the value, the value would be changed for all objects of type Animal.

A static class is one whose members are all static. Static classes, methods and fields are useful in certain scenarios for performance and efficiency reasons. However, subtle errors can arise if you assume that a field is an instance field when in fact it is static. For more information, see Static Classes and Static Class Members (C# Programming Guide).

Classes vs. Files

Every C# program has at least one class. When designing your program, it is good practice, but not a requirement, to keep a single class in each source code (.cs) file. If you use the C# integrated development environment (IDE) to create classes, it will automatically create a new source code file for you at the same time.

Члены экземпляра и статические члены37

Статический член представляет собой метод или поле, доступ к которым можно получить без ссылки на определенный экземпляр класса. Самый известный статический метод это Main, который представляет точку входа для всех программ C#; создавать экземпляр класса, содержащего метод Main, для вызова метода Main не нужно. Еще одним часто используемым в консольных приложениях статическим методом является метод WriteLine класса Console. При доступе к статическим методам необходимо обратить внимание на отличие в синтаксисе; с левой стороны оператора dot (точка) вместо имени экземпляра используется имя класса: Console.WriteLine.

Поле класса, объявляемое как статическое, будет общим для всех экземпляров класса. Если бы поле size в следующем примере кода было объявлено статическим и один из объектов класса Animal изменил бы значение поля size, то это значение было бы изменено для всех объектов типа Animal.

Могут существовать статические классы, все элементы которых статические. Использование статических классов, методов и полей целесообразно в ряде случаев для повышения производительности и эффективности.

Классы и файлы

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

Encapsulation

A class typically represents the characteristics of a thing, and the actions that it can perform. For example, to represent an animal as a C# class, you might give it a size, speed, and strength represented as numbers, and some functions such as MoveLeft(), MoveRight(), SpeedUp(), Stop() and so on, in which you would write the code to make your "animal" perform those actions. In C#, your animal class would look like this:

public class Animal

{

private int size;

private float speed;

private int strength;

public void MoveLeft() // method

{

// code goes here...

}

// other methods go here...

}

If you browse through the .NET Framework Class Library, you will see that each class represents a "thing," such as an XmlDocument, a String, a Form, and that each thing has various actions that it can perform (methods), characteristics that you can read and perhaps modify (properties) and notifications (events) that it sends out when it performs some given action. The methods, properties and events, along with all the other internal variables and constants (fields), are referred to as the members of the class.

Grouping members together into classes is not only logical, it also enables you to hide data and functions that you do not want other code to have access to. This principle is known as encapsulation. When you browse the .NET Framework class libraries, you are seeing only the public members of those classes. Each class probably also has private members that are used internally by that class or classes related to it, but are not meant to be used by applications. When you create your own classes, you will decide which members should be public, and which should be private.