我无法理解.NET 世界中代表的正确使用。代理不能解决什么问题?我想知道什么场景/情况是代表使用的理想或候选者。
我知道 LINQ 和 Lambda 表达式都在幕后使用 Delegates。我知道如何创建和使用它,但我不明白为什么我应该创建和使用它们?
任何现实世界的例子或经验分享都将受到高度赞赏。
更新:
我创建了以下课程
using System;
using System.Collections.Generic;
using System.Linq;
namespace Basics
{
public class Program
{
static void Main()
{
Flight.FlightTakeOffDelegate flightDelegate;
var flights = new List<Flight>
{
new Flight {Number = "FL001", DepartureTime = DateTime.Now, TotalCrew = 15},
new Flight {Number = "FL002", DepartureTime = DateTime.Now.AddHours(1), TotalCrew = 15},
new Flight {Number = "FL003", DepartureTime = DateTime.Now.AddHours(2), TotalCrew = 15},
};
var tower = new FlightTower(flights);
// Flight 002 asking to Take off
var flightAskingToTakeOff = flights.FirstOrDefault(x => x.Number == "FL002");
if (flightAskingToTakeOff != null)
{
Console.WriteLine(string.Format("Flight {0} \t: Okay to take off?", flightAskingToTakeOff.Number));
flightDelegate = tower.CanTakeOff;
flightAskingToTakeOff.CanTakeOff = flightDelegate.Invoke(flightAskingToTakeOff);
Console.WriteLine(string.Format("Flight Tower \t: {0}", flightAskingToTakeOff.CanTakeOff));
}
// Flight 001 asking to Take off
flightAskingToTakeOff = flights.FirstOrDefault(x => x.Number == "FL001");
if (flightAskingToTakeOff != null)
{
Console.WriteLine(string.Format("Flight {0} \t: Okay to take off?", flightAskingToTakeOff.Number));
flightDelegate = tower.CanTakeOff;
flightAskingToTakeOff.CanTakeOff = flightDelegate.Invoke(flightAskingToTakeOff);
Console.WriteLine(string.Format("Flight Tower \t: {0}", flightAskingToTakeOff.CanTakeOff));
}
Console.ReadKey();
}
}
public class FlightTower
{
private readonly List<Flight> _schedule;
public FlightTower(List<Flight> schedule)
{
_schedule = schedule;
}
public bool CanTakeOff(Flight flight)
{
var arrivingFlights = _schedule.Where(x => x.ArrivalTime == DateTime.Now);
if (!arrivingFlights.Any())
{
var flightInQueue = _schedule.FirstOrDefault(x => x.DepartureTime == _schedule.Min(c=> c.DepartureTime));
if (flightInQueue != null && flightInQueue.Number == flight.Number)
{
return true;
}
}
return false;
}
}
public class Flight
{
public delegate bool FlightTakeOffDelegate(Flight flight);
public string Number { get; set; }
public DateTime DepartureTime { get; set; }
public DateTime ArrivalTime { get; set; }
public int TotalCrew { get; set; }
public bool CanTakeOff { get; set; }
}
}
任何人都可以看看如何在这种情况下使用代表?