Назад

Глава 5

Программа CarDelegate


using System;
//using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace CarDelegate
{

public class Car
{
//Новые переменные!
private bool isDirty; //испачкан ли наш авто?
private bool shouldRotate; //нужна ли замена шин?

//Свойство для isDirty
public bool Dirty
{

get {return isDirty;}
set {isDirty = value;}
}

//Свойство для shouldRotate
public bool Rotate
{

get {return shouldRotate;}
set {shouldRotate = value;}
}

#region Basic Car members...

// Internal state data.
private int currSpeed;
private int maxSpeed;
private string petName;

public Car()
{

maxSpeed = 100;
}

public Car(string name, int max, int curr)
{

currSpeed = curr;
maxSpeed = max;
petName = name;
}

//Конструктор с новыми параметрами
public Car(string name, int max, int curr, bool dirty, bool rotate)
{

currSpeed = curr;
maxSpeed = max;
petName = name;
isDirty = dirty;
shouldRotate = rotate;
}

#endregion

//Делегат - это класс, инкапсулирующий указатель на функцию.В нашем случае
//этой функцией должен стать какой-то метод, принимающий в качестве
//параметра объект класса Car и ничего не возвращающий:

public delegate void CarDelegate(Car c);

}

public class Garage
{

// We have some cars.
ArrayList theCars = new ArrayList();

public Garage()
{

theCars.Add(new Car("Viper", 100, 0, true, false));
theCars.Add(new Car("Fred", 100, 0, false, false));
theCars.Add(new Car("BillyBob", 100, 0, false, true));
theCars.Add(new Car("Bart", 100, 0, true, true));
theCars.Add(new Car("Stan", 100, 0, false, true));

}

// This method takes a CarDelegate as a parameter.
// Therefore! 'proc' is nothing more than a function pointer...

public void ProcessCars(Car.CarDelegate proc)
{

// Where are we passing the call?
foreach (Delegate d in proc.GetInvocationList())
{
Console.WriteLine("***** Calling: {0} *****", d.Method);
}

// Am I calling an object's method or a static method?
if (proc.Target != null)

Console.WriteLine("\n-->Target: {0}", proc.Target);
else
Console.WriteLine("\n-->Target is a static method");

// Now call method for each car.
foreach (Car c in theCars)
{

Console.WriteLine("\n-> Processing a Car");
proc(c);
}
Console.WriteLine();
}
}


class CarApp
{

public static void WashCar(Car c)
{
if(c.Dirty)
Console.WriteLine("Cleaning a car");
else
Console.WriteLine("This car is already clean ...");
}

public static void RotateTires(Car c)
{

if(c.Rotate)
Console.WriteLine("Tires have been rotated");
else
Console.WriteLine(" Dont need to be rotated ...");
}

static void Main(string[] args)
{

// Console.WriteLine("***** Even More Delegates *****\n");

// Make the garage.
Garage g = new Garage();

// Wash all dirty cars.
g.ProcessCars(new Car.CarDelegate(WashCar));

// Rotate the tires.
g.ProcessCars(new Car.CarDelegate(RotateTires));

Console.ReadLine();

}
}
}



Назад