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

Классы и объекты

Класс, по сути, является чертежом для пользовательского типа данных. Определив класс, его можно использовать, загрузив в память. Класс, загруженный в память, называется объектом или экземпляром. Экземпляр класса создается с помощью ключевого слова C# new.

Далее представлен пример определения класса с именем SampleClass и создание объекта с именем sampleClass1, который является экземпляром этого класса. Поскольку необходимо, чтобы функция Main была определена внутри класса, в следующем коде также определяется класс Program, однако он не используется для создания объекта.

using System;

class SampleClass

{

public void SayHello()

{

Console.WriteLine("Hello, World!");

}

}

class Program

{

//Main is the entrypoint, where every C# program starts

static void Main(string[] args)

{

SampleClass sampleClass1 = new SampleClass(); // Create an object

sampleClass1.SayHello(); // Call a method

}

}

Подобно тому, как на основе одного чертежа можно построить несколько зданий, можно создать любое количество объектов одного класса. Очень часто используются массивы или списки, содержащие множество объектов одного класса. Каждый экземпляр класса занимает отдельную область памяти; значения его полей (исключая статические поля, как описано далее) также являются независимыми. В представленном ниже примере кода создается один объект типа Animal, ему задается размер "2", и другой объект с размером "3". Однако для этого правила существует важное исключение, а именно статический член.

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.

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