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

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

В каждом классе существует конструктор — метод с тем же именем, что и у класса. Конструктор вызывается при создании объекта на базе определения класса. Обычно конструкторы задают начальные значения переменных, определенных в классе. Конструкторы не используются, если начальным значением для числовых типов данных будет ноль, "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# системы автоматического сбора мусора маловероятно, что вам когда-либо придется применять деструктор, если только класс не использует неуправляемые ресурсы.

How to: Call a Method on an Object

This example calls an instance method, myMthod, referenced through an instance of the class.

Example

class Program

{

static void Main(string[] args)

{

Program myObject = new Program();

myObject.myMethod();

}

void myMethod()

{

// Do something

}

}

Compiling the Code

Copy the code, and paste it into a console application and build the solution.

Robust Programming

Use the fully qualified name of the method, unless it is accessible from the same scope.

If the method is static, you should not reference it through an instance of the class.

When assigning an expression to a property, make sure of the following:

  • That it is of a compatible data type.

  • That it has a valid value, especially if the value is derived from user input.

Вызов метода в объекте

В этом примере вызывается метод экземпляра myMthod, на который осуществлена ссылка с помощью экземпляра класса.

Пример

class Program

{

static void Main(string[] args)

{

Program myObject = new Program();

myObject.myMethod();

}

void myMethod()

{

// Do something

}

}

Компиляция кода

Скопируйте код, вставьте его в консольное приложение и постройте решение.

Надежное программирование

Воспользуйтесь полным именем метода (если только оно недоступно из той же области действия).

Если метод является статическим, ссылаться на него с помощью экземпляра класса нельзя.

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

  • Используется совместимый тип данных.

  • Используется допустимое значение, особенно, если оно извлекается из введенных пользователем данных.

How to: Inherit From a Class

This example defines the Circle and Rectangle classes, which both inherit from the Shape class, and the Square class, which inherits from the Rectangle class.

Example

public class Shape

{

// Definitions of properties, methods, fields, and events.

}

public class Circle : Shape

{

// Specialized properties, methods, fields, events for Circle.

}

public class Rectangle : Shape

{

// Specialized properties, methods, fields, events for Rectangle.

}

public class Square : Rectangle

{

// Specialized properties, methods, fields, events for Square.

}

Compiling the Code

  • Start a new console application.

  • Copy the code and paste it right before or after Class1 declaration.

Robust Programming

Make sure the class you want to inherit is not sealed.

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

В этом примере определяются классы Circle и Rectangle, которые оба наследуют от класса Shape, и класс Square, наследуемый от класса Rectangle.

Пример

public class Shape

{

// Definitions of properties, methods, fields, and events.

}

public class Circle : Shape

{

// Specialized properties, methods, fields, events for Circle.

}

public class Rectangle : Shape

{

// Specialized properties, methods, fields, events for Rectangle.

}

public class Square : Rectangle

{

// Specialized properties, methods, fields, events for Square.

}

Компиляция кода

  • Запустите новое консольное приложение.

  • Скопируйте и вставьте код до или после объявления Class1.36

Надежное программирование

Убедитесь, что класс, от которого вы хотите наследовать, не является запечатанным.

How to: Simulate Default Parameters

This example demonstrates the use of method overloading to simulate default parameters, which is not allowed in C#.

Example

class MyClass

{

static string myMethod(string precip, string country, string location)

{

return string.Format("The {0} in {1} stays mainly in the {2}.",

precip, country, location );

}

static string myMethod(string precip, string country )

{

return myMethod(precip, country, "plain");

}

static string myMethod()

{

return myMethod("rain", "Spain", "plain");

}

static void Main(string[] args)

{

System.Console.WriteLine(myMethod());

System.Console.WriteLine(myMethod("snow", "Walla Walla"));

}

}

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