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

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

В этом примере создается экземпляр myObject класса Program и этот экземпляр вызывает метод myMethod класса Program

Пример

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.39

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"));

}

}

Compiling the Code

Copy the class and paste it over Class1 in a console application.

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