Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю - Страница 153
- Предыдущая
- 153/642
- Следующая
Изменить размер шрифта:
153
Кроме того, класс
Car
Car
Car
using System;
namespace SimpleException
{
class Car
{
// Константа для представления максимальной скорости.
public const int MaxSpeed = 100;
// Свойства автомобиля.
public int CurrentSpeed {get; set;} = 0;
public string PetName {get; set;} = "";
// He вышел ли автомобиль из строя?
private bool _carIsDead;
// В автомобиле имеется радиоприемник.
private readonly Radio _theMusicBox = new Radio();
// Конструкторы.
public Car() {}
public Car(string name, int speed)
{
CurrentSpeed = speed;
PetName = name;
}
public void CrankTunes(bool state)
{
// Делегировать запрос внутреннему объекту.
_theMusicBox.TurnOn(state);
}
// Проверить, не перегрелся ли автомобиль.
public void Accelerate(int delta)
{
if (_carIsDead)
{
Console.WriteLine("{0} is out of order...", PetName);
}
else
{
CurrentSpeed += delta;
if (CurrentSpeed > MaxSpeed)
{
Console.WriteLine("{0} has overheated!", PetName);
CurrentSpeed = 0;
_carIsDead = true;
}
else
{
Console.WriteLine("=> CurrentSpeed = {0}",
CurrentSpeed);
}
}
}
}
}
Обновите код в файле
Program.cs
Car
100
Car
using System;
using System.Collections;
using SimpleException;
Console.WriteLine("***** Simple Exception Example *****");
Console.WriteLine("=> Creating a car and stepping on it!");
Car myCar = new Car("Zippy", 20);
myCar.CrankTunes(true);
for (int i = 0; i < 10; i++)
{
myCar.Accelerate(10);
}
Console.ReadLine();
В результате запуска кода будет получен следующий вывод:
***** Simple Exception Example *****
=> Creating a car and stepping on it!
Jamming...
=> CurrentSpeed = 30
=> CurrentSpeed = 40
=> CurrentSpeed = 50
=> CurrentSpeed = 60
=> CurrentSpeed = 70
=> CurrentSpeed = 80
=> CurrentSpeed = 90
=> CurrentSpeed = 100
Zippy has overheated!
Zippy is out of order...
Генерация общего исключения
Теперь, имея функциональный класс
Car
Accelerate()
Чтобы модернизировать метод
Accelerate()
System.Exception
Message
throw
Accelerate()
153
- Предыдущая
- 153/642
- Следующая
Перейти на страницу: