我很抱歉发布了这么多代码,但在这种情况下,我觉得这个问题更容易理解,尽管这个问题可能非常简单(我希望答案同样简单)。
我正在玩活动和代表。在我的 Main 方法中,我有代码
traffic.PutInGarage(g);
这意味着我正在传递我的 Garage 类的引用(参见下面的代码)。这是您期望事件通过的方式吗?我不知道为什么,我无法解释为什么,感觉不对,好像我在某些地方错过了重点。
再次,很抱歉发布所有控制台应用程序代码,但它可能更容易。
using System;
using System.Collections.Generic;
namespace DemoProejct
{
public class Program
{
public static void Main(string[] args)
{
Garage g = new Garage();
g.NewCarEvent += new Garage.NewCarDelegate(GarageCount);
Traffic traffic = new Traffic();
//SHOULD I BE PASSING THE Garage object here?
traffic.PutInGarage(g);
Console.WriteLine("Garage is now closed");
Console.ReadKey();
}
private static void GarageCount(string cars, string s)
{
Console.WriteLine(string.Format("{0} {1}", cars, s));
System.Threading.Thread.Sleep(2000);
}
}
public class Traffic
{
public void PutInGarage(Garage g)
{
List<Vehicle> all = GetVehicles();
Vehicle modelWeFix = new Vehicle() { Make = "Mazda", Model = "6", Year = "2012" };
int i = 1;
foreach (IEquatabled<Vehicle> item in all)
{
if (item.EqualsTo(modelWeFix))
{
g.CarsInGarage = i;
i++;
}
}
}
private List<Vehicle> GetVehicles()
{
Car carMazda = new Car() { Make = "Mazda", Model = "6", Year = "2012" };
Car carFord = new Car() { Make = "Ford", Model = "Sport", Year = "2002" };
Car carUnknown = new Car() { Make = "Mazda", Model = "5", Year = "2012" };
Bike mazdaBike = new Bike() { Make = "Mazda", Model = "6", Year = "2012" };
IEquatabled<Vehicle> unknownBike = mazdaBike;
List<Vehicle> all = new List<Vehicle>();
all.Add(carMazda);
all.Add(carFord);
all.Add(carUnknown);
all.Add(mazdaBike);
return all;
}
}
public class Garage
{
public delegate void NewCarDelegate(string numberOfCars, string message);
public event NewCarDelegate NewCarEvent;
private int _carsInGarage;
public int CarsInGarage
{
get { return _carsInGarage; }
set
{
if (NewCarEvent != null)
{
_carsInGarage = value;
NewCarEvent(value.ToString(), " cars in the garage.");
}
}
}
public Garage()
{
CarsInGarage = 0;
}
}
public class Vehicle : IEquatabled<Vehicle>
{
public string Make { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public virtual int Wheels { get; set; }
//Implementation of IEquatable<T> interface
public bool EqualsTo(Vehicle car)
{
if (this.Make == car.Make && this.Model == car.Model && this.Year == car.Year)
return true;
else
return false;
}
}
public class Car : Vehicle
{}
public class Bike : Vehicle
{}
interface IEquatabled<T>
{
bool EqualsTo(T obj);
}
}