我很抱歉發佈了這麼大的一段代碼,但在這種情況下,我覺得這會更容易理解這個問題,儘管問題可能很簡單(同樣簡單的答案我希望)。在.NET中傳遞事件
我正在玩事件和代表。在我的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);
}
}
當然,該方法應該在'Garage'對象上? 'Garage.StoreTraffic(交通)' - 實施似乎倒退。交通不應該負責車庫的行爲... – Charleh 2013-02-28 15:25:14
對不起,有什麼問題嗎? _這是你期望事件被傳遞的方式嗎?_你不傳遞事件 - 你傳遞實例。 – 2013-02-28 15:25:37
@Charleh - 我想你已經釘了它!我一直試圖理解事件,完成事件,代表和繼承,我不認爲我能看到樹木的木材!謝謝。 – Dave 2013-02-28 15:28:08