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.


Инкапсуляция

Обычно класс определяет характеристики объекта и выполняемые им действия. Например, чтобы определить класс животного в C#, необходимо задать ему размер, скорость и силу, представленными в виде чисел, а также некоторые функции, например MoveLeft(), MoveRight(), SpeedUp(), Stop() и так далее, в которых можно написать код для выполнения "животным" этих действий. В C# класс животного может выглядеть следующим образом.

public class Animal { private int size; private float speed; private int strength; public void MoveLeft() // method { // code goes here... } // other methods go here... }

При знакомстве с .NET Framework Class Library будет ясно, что каждый класс представляет собой "нечто", например XmlDocument, String, Form, и для каждого такого "нечто" существуют различные действия, которые оно может выполнить (методы), характеристики, которые можно прочитать и изменить (свойства), и уведомления (события), формируемые при совершении тех или иных действий. Методы, свойства и события, а также все остальные внутренние переменные и постоянные характеристики (поля) называются членами класса.

Группировка членов в классы имеет не только логический смысл, она также позволяет скрывать данные и функции, которые должны быть недоступны для другого кода. Этот принцип называют инкапсуляцией. При использовании классов из библиотек платформы .NET Framework будут видны только открытые члены этих классов. Каждый класс может иметь закрытые члены, используемые либо только внутри этого класса, либо определенными связанными с ним классами. Закрытые члены не предназначены для использования приложениями, использующими сам класс. Создавая собственные классы, нужно решить, какие члены будут открытыми, а какие — закрытыми.


Inheritance

A class can inherit another class, which means that it includes all the members, public and private, of the original class, plus the additional members that it defines. The original class is called the base class and the new class is called the derived class. You create a derived class to represent something that is a more specialized kind of the base class. For example, you could define a class Cat that inherits from Animal. A Cat can do everything an Animal can do, plus it can perform one additional unique action. The C# code looks like this:

public class Cat : Animal { public void Purr() { } }

The Cat : Animal notation indicates that Cat inherits from Animal and that therefore Cat also has a MoveLeft method and the three private variables size, speed, and strength. If you define a SiameseCat class that inherits from Cat, it will have all the members of Cat plus all the members of Animal.

Polymorphism

In the field of computer programming, polymorphism refers to the ability of a derived class to redefine, or override, methods that it inherits from a base class. You do this when you need to do something specific in a method that is either different or else not defined in the base class. For example, the Animal.MoveLeft method, since it must be very general in order to be valid for all animals, is probably very simple: something like "change orientation so that animal's head is now pointing in direction X". However, in your Cat class, this might not be sufficient. You might need to specify how the Cat moves its paws and tail while it turns. And if you have also defined a Fish class or a Bird class, you will probably need to override the MoveLeft method in different ways for each of those classes also. Because you can customize the behavior of the MoveLeft method for your particular class, the code that creates your class and calls its methods does not have a separate method for each animal in the world. As long as the object inherits from Amimal, the calling code can just call the MoveLeft method and the object's own version of the method will be invoked.


Наследование

Класс может наследовать от другого класса. Это означает, что он наследуемый класс включает все члены — открытые и закрытые — исходного класса. Кроме того наследуемый класс может определять дополнительные члены. Исходный класс называется базовым классом (или классом-предком) а новый класс — производным классом (или классом-наследником) Производный класс создается для специализации возможностей базового класса. Например, можно определить класс Cat, который наследует от Animal. Cat может выполнять все то же, что и Animal, но дополнительно еще урчать. Код C# класса Cat, наследующего от класса Animal, выглядит следующим образом.

public class Cat : Animal { public void Purr() { } }

Нотация Cat : Animal означает, что Cat наследует от Animal и что Cat также имеет метод MoveLeft и три закрытых поля: size, speed и strength. Если определяется класс SiameseCat, который наследует от Cat, он будет содержать все члены Cat, а также все члены Animal.

 

Полиморфизм

В сфере компьютерного программирования полиморфизмом называют возможность производного класса изменять или переопределять методы, которые он наследует от базового класса. Эта возможность используется, если нужно выполнить какие-то особые действия в методе, который отличается от базового, либо не определен в базовом классе,. Например, поскольку метод Animal.MoveLeft должен быть общим, чтобы подходить для всех животных, он является, возможно, очень простым, как например "изменение положения так, чтобы голова животного была в направлении X". Однако для класса Cat этого может быть недостаточно. Может потребоваться указать, как Cat двигает лапами и хвостом при поворотах. Или, к примеру, если описывается класс Fish или класс Bird, то, возможно, потребуется описать в каждом из этих классов свой метод MoveLeft. Поскольку можно настроить поведение метода MoveLeft для конкретного класса, в коде, создающем объект класса Animal и его наследников, отсутствует вызов отдельного метода для каждого животного. Пока объект наследует от Animal, достаточно, чтобы код вызывал метод MoveLeft. При этом будет вызвана та версия метода MoveLeft, которая соответствует конкретному типу животного-объекта в момент обращения к методу.


Constructors

Every class has a constructor: a method that shares the same name as the class. The constructor is called when an object is created based on the class definition. Constructors typically set the initial values of variables defined in the class. This is not necessary if the initial values are to be zero for numeric data types, false for Boolean data types, or null for reference types, as these data types are initialized automatically.

You can define constructors with any number of parameters. Constructors that do not have parameters are called default constructors. The following example defines a class with a default constructor and a constructor that takes a string, and then uses each:

class SampleClass { string greeting;   public SampleClass() { greeting = "Hello, World"; } public SampleClass(string message) { greeting = message; }   public void SayHello() { System.Console.WriteLine(greeting); } } class Program { static void Main(string[] args) { // Use default constructor. SampleClass sampleClass1 = new SampleClass(); sampleClass1.SayHello(); // Use constructor that takes a string parameter. SampleClass sampleClass2 = new SampleClass("Hello, Mars"); sampleClass2.SayHello(); } }

Конструкторы

В каждом классе существует конструктор — метод с тем же именем, что и у класса. Конструктор вызывается при создании объекта на базе определения класса. Обычно конструкторы задают начальные значения переменных, определенных в классе. Конструкторы не используются[38], если начальным значением для числовых типов данных будет ноль, "false" для логических типов данных или null для ссылочных типов, поскольку эти типы данных инициализируются автоматически.

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

class SampleClass{ string greeting; public SampleClass() { greeting = "Hello, World"; } public SampleClass(string message) { greeting = message; } public void SayHello() { System.Console.WriteLine(greeting); }}class Program{ static void Main(string[] args) { // Use default constructor. SampleClass sampleClass1 = new SampleClass(); sampleClass1.SayHello(); // Use constructor that takes a string parameter. SampleClass sampleClass2 = new SampleClass("Hello, Mars"); sampleClass2.SayHello(); }}

Operator Overloading

Creating different methods with the same name, in the previous example SampleClass(), is called overloading. The compiler knows which method to use because the list of arguments, if there are any, is provided each time an object is created. Overloading can make your code more flexible and readable.

Destructors

You may already know about destructors if you have used C++. Because of the automatic garbage collection system in C#, it is not likely that you will ever have to implement a destructor unless your class uses unmanaged resources. For more information, see Destructors (C# Programming Guide).


Перегрузка методов

Перегрузкой называется создание разных методов с одним именем. В предыдущем примере такими методами являются конструкторы SampleClass(). Компилятору известно, какой метод следует использовать, поскольку во время каждого создания объекта предоставляется список аргументов (если таковые имеются). Перегрузка может сделать код более гибким и удобочитаемым.

Деструкторы

Если вы работали с C++, то, возможно, вы уже располагаете сведениями о деструкторах. В связи с наличием в C# системы автоматического сбора мусора маловероятно, что вам когда-либо придется применять деструктор, если только класс не использует неуправляемые ресурсы.




Дата добавления: 2022-05-27; просмотров: 196;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.012 сек.