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

Создание собственного пространства имен

Обычно пространства имен используются при работе с большими программами. Собственные пространства имен предоставляют определенный уровень контроля над методами и типами с одинаковыми именами. Например, предположим, что выполняется написание приложения, загружающего с диска статистические данные и файлы изображений. Можно создать два новых пространства имен, одно с именем Images, а другое — StatisticalData. Поскольку используются два отдельных пространства, все имена методов, определенные в каждом из них, будут уникальными, даже если отдельные классы имеют одинаковые имена. Предположим, что в обоих пространствах находится класс с именем FileHandling и в каждом классе есть метод с именем Load. Для указания нужного класса можно обратиться к StatisticalData.FileHandling или Images.FileHandling.

Для каждого пространства имен в проекте Visual C# рекомендуется создать отдельную папку.

Example

The following example defines two namespaces, each containing a class named FileHandling. By specifying the namespace, it's possible to quickly differentiate between the classes and the methods they contain.

namespace StatisticalData

{

class FileHandling

{

public void Load() {} // code to load statistical data

}

}

namespace Images

{

class FileHandling

{

public void Load() {} // code to load an image file

}

}

class Program

{

static void Main()

{

StatisticalData.FileHandling data = new StatisticalData.FileHandling();

data.Load();

Images.FileHandling image = new Images.FileHandling();

image.Load();

}

}

Пример

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

------

Classes

C# is an object-oriented programming language, and in common with other modern languages, it groups related fields, methods, properties, and events into data structures called classes.

Classes vs. Objects

A class is basically a blueprint for a custom data type. Once you define a class, you use it by loading it into memory. A class that has been loaded into memory is called an object or an instance. You create an instance of a class by using the C# keyword new.

Here is an example of a class definition called SampleClass, and the creation of an object called sampleClass1 that is an instance of that class. Because C# requires that the Main function be defined inside a class, the following code also defines a Program class, but that class is not used to create an object.

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

}

}

Just as you can build any number of houses based on the same blueprint, you can instantiate any number of objects of the same class. It is very common to have arrays or lists that contain many objects of the same class. Each instance of the class occupies a separate memory space and the values of its fields (except its static fields as discussed below) are separate and independent. In the code example below, you could create one object of type Animal and set its size to 2, and another object whose size you set to 3. However, there is an important exception to this rule, and that is the static member.

Классы

C# является объектно-ориентированным языком программирования и аналогично другим современным языкам группирует связанные поля, методы, свойства и события в структуры данных, которые называются классами.

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