不明白的代表在现实世界中的场景使用 [英] Failed to Understand the Use of Delegates in Real World Scenarios

查看:108
本文介绍了不明白的代表在现实世界中的场景使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白在.NET世界的正确使用代表。有什么不能代表来解决?我想知道什么情况/情况是理想或候选人,代表使用。

I can't understand the proper use of delegates in .NET world. What can't be solved with Delegates? I want to know what scenario/situation is ideal or candidate for delegate usage.

我知道LINQ和Lambda表达式都使用在幕后代表。我知道如何创建和使用它,但我没能明白的是为什么要创建和使用它们?

I know LINQ and Lambda expressions all use Delegates behind the scenes. I know how to create and consume it but what I have failed to understand is WHY I should create and use them?

任何现实世界的例子,或分享经验将高度赞赏

Any real world example or experience sharing would be highly appreciated.

更新:

我创建了以下类

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; }
}



}

}

任何人都可以请看看,看看如何能代表在这样的场景中使用??

Can anyone please have a look to see how can delegates be used in such scenario??

推荐答案

代表不允许你来执行,你已经不能执行任务,但他们让你实现与更清洁,更模块化的代码相同的结果。这个概念是非常相似的背后泛型/接口或抽象类的实现,但它适用于操作和功能,而不是对象和属性。

Delegates don't allow you to perform tasks that you can't already perform, but they allow you to achieve the same outcome with much cleaner and more modular code. The concept is very similar to that behind generics/interfaces, or implementations of abstract classes, but it works for actions and functions rather than objects and properties.

因此,让我们说你有一类机场的控制飞机(称之为 FlightTower ),和一些不同的面。每架飞机知道的所有本身 - 当它应该离开,每个人是否在船上 - 但它不知道其他飞机,或跑道是否清晰,或其他任何东西。

So let's say you have a class the controls airplanes in an airport (call it FlightTower), and a number of different planes. Each plane knows about all itself - when it is supposed to leave, whether everyone is on board - but it doesn't know about the other planes, or whether the runway is clear, or anything else.

非代表的办法是给每一个平面访问 FlightTower 来弄清楚什么时候起飞。它可以浏览该 FlightTower 知道飞机的列表,了解他们在做什么,并与其他飞机甚至是协调。想象一下,每架飞机有它连接到 FlightTower 系统检查是怎么回事一台电脑;每个飞行员需要知道如何使用该系统,并找出在安全去。

The non-delegate approach is to give each plane access to the FlightTower to figure out when to take off. It can look through a list of planes that the FlightTower knows about, find out what they are doing, and even coordinate with other planes. Imagine each plane had a computer which connects to the FlightTower system to check what's going on; and each pilot needs to know how to use that system and figure out when it's safe to go.

的委托方法将是 FlightTower 来给飞机检查是否起飞的方法。当飞机到达时, FlightTower 机场给他们带来了一些无线电指令 - 他们可以问没事起飞'和 FlightTower 会给他们一个答案。飞机并不需要做任何事情了自己的思考。

The delegate approach would be for the FlightTower to give the plane a method to check whether to take off. When the plane arrives at the airport, the FlightTower gives them a few radio commands - they can ask 'okay to take off' and the FlightTower will give them an answer. The plane doesn't need to do anything thinking of its own.

有关委托方法的很酷的事情是, FlightTower 可以做的,当飞机问的问题不管它喜欢的(假设它给出了正确的答案)。它可以计算出一个答案本身,它可以发送查询了一些调度系统,或其他任何东西。这是代表团的核心理念发挥出 - 飞机'代表'的过程中对 FlightTower

The cool thing about the delegate approach is that the FlightTower can do whatever it likes when the plane asks the question (assuming it gives the correct answer). It can figure out an answer itself, it can send the query off to some scheduling system, or anything else. This is where the core of the delegation concept plays out - the plane 'delegates' the process to the FlightTower.

这篇关于不明白的代表在现实世界中的场景使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆