C# 代表和事件之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 08:18:44  来源:igfitidea点击:

What are the differences between delegates and events?

提问by Sean Chambers

What are the differences between delegates and an events? Don't both hold references to functions that can be executed?

委托和事件之间有什么区别?不是都持有对可以执行的函数的引用吗?

采纳答案by mmcdole

An Eventdeclaration adds a layer of abstraction and protection on the delegateinstance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

一个事件的声明增加了抽象和保护上一层委托实例。此保护可防止委托的客户端重置委托及其调用列表,并且仅允许在调用列表中添加或删除目标。

回答by Jorge Córdoba

In addition to the syntactic and operational properties, there's also a semantical difference.

除了句法和操作属性之外,还有语义差异。

Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

从概念上讲,委托是函数模板;也就是说,它们表达了一个函数必须遵守的契约,以便被认为是委托的“类型”。

Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.

事件代表......好吧,事件。它们旨在在发生某些事情时提醒某人,是的,它们遵循委托定义,但它们不是一回事。

Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).

即使它们完全相同(在语法上和在 IL 代码中),语义上的差异仍然存在。一般来说,我更喜欢为两个不同的概念使用两个不同的名称,即使它们以相同的方式实现(这并不意味着我喜欢两次使用相同的代码)。

回答by Paul Hill

You can also use events in interface declarations, not so for delegates.

您还可以在接口声明中使用事件,而不是委托。

回答by supercat

An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.

.net 中的事件是 Add 方法和 Remove 方法的指定组合,这两种方法都需要某种特定类型的委托。C# 和 vb.net 都可以为 add 和 remove 方法自动生成代码,这些代码将定义一个委托来保存事件订阅,并向/从该订阅委托添加/删除传入的委托。当且仅当订阅列表非空时,VB.net 也会自动生成代码(使用 RaiseEvent 语句)来调用订阅列表;出于某种原因,C# 不会生成后者。

Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.

请注意,虽然使用多播委托管理事件订阅很常见,但这并不是这样做的唯一方法。从公共角度来看,潜在的事件订阅者需要知道如何让对象知道它想要接收事件,但它不需要知道发布者将使用什么机制来引发事件。还要注意,虽然在 .net 中定义事件数据结构的人显然认为应该有一种公开的方式来提高它们,但 C# 和 vb.net 都没有使用该功能。

回答by vibhu

Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx

这是另一个可供参考的好链接。 http://csharpindepth.com/Articles/Chapter2/Events.aspx

Briefly, the take away from the article - Events are encapsulation over delegates.

简而言之,本文的要点 - 事件是对委托的封装。

Quote from article:

引自文章:

Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event? Three options:

  1. A public delegate variable

  2. A delegate variable backed by a property

  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

Option 1 is clearly horrible, for all the normal reasons we abhor public variables.

Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.

Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.

假设事件在 C#/.NET 中不作为一个概念存在。另一个类将如何订阅事件?三个选项:

  1. 公共委托变量

  2. 由属性支持的委托变量

  3. 具有 AddXXXHandler 和 RemoveXXXHandler 方法的委托变量

选项 1 显然很糟糕,出于我们厌恶公共变量的所有正常原因。

选项 2 稍微好一点,但允许订阅者有效地相互覆盖 - 编写 someInstance.MyEvent = eventHandler; 太容易了。这将替换任何现有的事件处理程序,而不是添加一个新的事件处理程序。此外,您仍然需要编写属性。

选项 3 基本上是事件为您提供的内容,但有保证的约定(由编译器生成并由 IL 中的额外标志支持)和“免费”实现(如果您对类事件给您的语义感到满意)。订阅和取消订阅事件被封装起来,不允许任意访问事件处理程序列表,并且语言可以通过为声明和订阅提供语法来使事情变得更简单。

回答by faby

To understand the differences you can look at this 2 examples

要了解差异,您可以查看这两个示例

Example with Delegates (in this case, an Action - that is a kind of delegate that doesn't return a value)

委托示例(在本例中,是一个 Action - 即一种不返回值的委托)

public class Animal
{
    public Action Run {get; set;}

    public void RaiseEvent()
    {
        if (Run != null)
        {
            Run();
        }
    }
}

To use the delegate, you should do something like this:

要使用委托,您应该执行以下操作:

Animal animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();

This code works well but you could have some weak spots.

此代码运行良好,但您可能有一些弱点。

For example, if I write this:

例如,如果我这样写:

animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;

with the last line of code, I have overridden the previous behaviors just with one missing +(I have used =instead of +=)

使用最后一行代码,我覆盖了以前的行为,只是缺少一个+(我使用了=而不是+=

Another weak spot is that every class which uses your Animalclass can raise RaiseEventjust calling it animal.RaiseEvent().

另一个弱点是每个使用您的Animal类的类都可以通过RaiseEvent调用它来引发animal.RaiseEvent()

To avoid these weak spots you can use eventsin c#.

为了避免这些弱点,您可以events在 c# 中使用。

Your Animal class will change in this way:

你的 Animal 类会以这种方式改变:

public class ArgsSpecial : EventArgs
{
    public ArgsSpecial (string val)
    {
        Operation=val;
    }

    public string Operation {get; set;}
} 

public class Animal
{
    // Empty delegate. In this way you are sure that value is always != null 
    // because no one outside of the class can change it.
    public event EventHandler<ArgsSpecial> Run = delegate{} 

    public void RaiseEvent()
    {  
         Run(this, new ArgsSpecial("Run faster"));
    }
}

to call events

调用事件

 Animal animal= new Animal();
 animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
 animal.RaiseEvent();

Differences:

区别:

  1. You aren't using a public property but a public field (using events, the compiler protects your fields from unwanted access)
  2. Events can't be assigned directly. In this case, it won't give rise to the previous error that I have showed with overriding the behavior.
  3. No one outside of your class can raise the event.
  4. Events can be included in an interface declaration, whereas a field cannot
  1. 您使用的不是公共属性,而是公共字段(使用事件,编译器会保护您的字段免受不必要的访问)
  2. 不能直接分配事件。在这种情况下,它不会引起我在覆盖行为时显示的先前错误。
  3. 班级以外的任何人都不能引发事件。
  4. 事件可以包含在接口声明中,而字段不能

Notes:

笔记:

EventHandler is declared as the following delegate:

EventHandler 被声明为以下委托:

public delegate void EventHandler (object sender, EventArgs e)

it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.

它需要一个发送者(对象类型)和事件参数。如果来自静态方法,则发送方为 null。

This example, which uses EventHandler<ArgsSpecial>, can also be written using EventHandlerinstead.

这个使用 的例子EventHandler<ArgsSpecial>也可以写成 using EventHandler

Refer herefor documentation about EventHandler

有关 EventHandler 的文档,请参阅此处

回答by Miguel Gamboa

What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class, or an interfacedoes), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.

事件和代表之间的巨大误解!!!委托指定 TYPE(例如 aclassinterfacedo),而事件只是一种 MEMBER(例如字段、属性等)。而且,就像任何其他类型的成员一样,事件也有一个类型。然而,在事件的情况下,事件的类型必须由委托指定。例如,您不能声明由接口定义的类型的事件。

Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining eventsof ECMA-335 (CLI) Partitions I to VI:

最后,我们可以进行以下观察:事件的类型必须由委托定义。这是一个事件和委托之间的主要关系,并在部分中描述II.18定义事件ECMA-335(CLI)分区I至VI

In typical usage, the TypeSpec (if present) identifies a delegatewhose signature matches the arguments passed to the event's fire method.

在典型用法中,TypeSpec(如果存在)标识一个委托,其签名与传递给事件的 fire 方法的参数相匹配。

However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers(note that event handlersare instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a Listor a Dictionaryor any other else, or even in a backing delegate field. But don't forget that it is NOT mandatory that you use a delegate field.

然而,这个事实并不意味着一个事件使用了一个支持委托字段。事实上,事件可以使用您选择的任何不同数据结构类型的支持字段。如果你在 C# 中显式地实现了一个事件,你可以自由选择你存储事件处理程序的方式(注意事件处理程序事件类型的实例,而事件类型又是强制性的委托类型——来自之前的观察)。但是,您可以将这些事件处理程序(它们是委托实例)存储在诸如 aList或 aDictionary或任何其他数据结构中,甚至可以存储在支持委托字段中。但是不要忘记使用委托字段不是强制性的。

回答by Trevor

NOTE: If you have access to C# 5.0 Unleashed, read the "Limitations on Plain Use of Delegates" in Chapter 18 titled "Events" to understand better the differences between the two.

注意:如果您可以访问C# 5.0 Unleashed,请阅读标题为“事件”的第 18 章中的“对普通使用委托的限制”以更好地了解两者之间的区别。



It always helps me to have a simple, concrete example. So here's one for the community. First I show how you can use delegates alone to do what Events do for us. Then I show how the same solution would work with an instance of EventHandler. And then I explain why we DON'T want to do what I explain in the first example. This post was inspired by an articleby John Skeet.

有一个简单、具体的例子总是对我有帮助。所以这是社区的一份。首先,我将展示如何单独使用委托来完成 Events 为我们所做的事情。然后我展示了相同的解决方案如何与EventHandler. 然后我解释为什么我们不想做我在第一个例子中解释的事情。这篇文章的灵感来自John Skeet的一篇文章

Example 1: Using public delegate

示例 1:使用公共委托

Suppose I have a WinForms app with a single drop-down box. The drop-down is bound to an List<Person>. Where Person has properties of Id, Name, NickName, HairColor. On the main form is a custom user control that shows the properties of that person. When someone selects a person in the drop-down the labels in the user control update to show the properties of the person selected.

假设我有一个带有单个下拉框的 WinForms 应用程序。下拉菜单绑定到List<Person>. Person 具有 Id、Name、NickName、HairColor 属性。主窗体上是一个自定义用户控件,显示该人的属性。当有人在下拉列表中选择一个人时,用户控件中的标签会更新以显示所选人员的属性。

enter image description here

在此处输入图片说明

Here is how that works. We have three files that help us put this together:

这是它的工作原理。我们有三个文件可以帮助我们将它们放在一起:

  • Mediator.cs -- static class holds the delegates
  • Form1.cs -- main form
  • DetailView.cs -- user control shows all details
  • Mediator.cs——静态类持有委托
  • Form1.cs -- 主窗体
  • DetailView.cs -- 用户控件显示所有细节

Here is the relevant code for each of the classes:

以下是每个类的相关代码:

class Mediator
{
    public delegate void PersonChangedDelegate(Person p); //delegate type definition
    public static PersonChangedDelegate PersonChangedDel; //delegate instance. Detail view will "subscribe" to this.
    public static void OnPersonChanged(Person p) //Form1 will call this when the drop-down changes.
    {
        if (PersonChangedDel != null)
        {
            PersonChangedDel(p);
        }
    }
}

Here is our user control:

这是我们的用户控件:

public partial class DetailView : UserControl
{
    public DetailView()
    {
        InitializeComponent();
        Mediator.PersonChangedDel += DetailView_PersonChanged;
    }

    void DetailView_PersonChanged(Person p)
    {
        BindData(p);
    }

    public void BindData(Person p)
    {
        lblPersonHairColor.Text = p.HairColor;
        lblPersonId.Text = p.IdPerson.ToString();
        lblPersonName.Text = p.Name;
        lblPersonNickName.Text = p.NickName;

    }
}

Finally we have the following code in our Form1.cs. Here we are Calling OnPersonChanged, which calls any code subscribed to the delegate.

最后,我们的 Form1.cs 中有以下代码。这里我们调用 OnPersonChanged,它调用订阅到委托的任何代码。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Mediator.OnPersonChanged((Person)comboBox1.SelectedItem); //Call the mediator's OnPersonChanged method. This will in turn call all the methods assigned (i.e. subscribed to) to the delegate -- in this case `DetailView_PersonChanged`.
}

Ok. So that's how you would get this working without using eventsand just using delegates. We just put a public delegate into a class -- you can make it static or a singleton, or whatever. Great.

好的。所以这就是你如何在不使用事件只使用委托的情况下工作。我们只是将一个公共委托放入一个类中——您可以将其设为静态或单例,或其他任何内容。伟大的。

BUT, BUT, BUT, we do not want to do what I just described above. Because public fields are badfor many, many reason. So what are our options? As John Skeet describes, here are our options:

但是,但是,但是,我们不想做我刚才描述的事情。因为公共领域有很多很多原因是不好的。那么我们有哪些选择呢?正如约翰·斯基特所描述的,以下是我们的选择:

  1. A public delegate variable (this is what we just did above. don't do this. i just told you above why it's bad)
  2. Put the delegate into a property with a get/set (problem here is that subscribers could override each other -- so we could subscribe a bunch of methods to the delegate and then we could accidentally say PersonChangedDel = null, wiping out all of the other subscriptions. The other problem that remains here is that since the users have access to the delegate, they can invoke the targets in the invocation list -- we don't want external users having access to when to raise our events.
  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods
  1. 一个公共委托变量(这是我们刚刚在上面所做的。不要这样做。我只是在上面告诉你为什么它不好)
  2. 将委托放入带有 get/set 的属性中(这里的问题是订阅者可以相互覆盖——所以我们可以为委托订阅一堆方法,然后我们可能会不小心说PersonChangedDel = null,清除所有其他订阅。这里仍然存在的另一个问题是,由于用户有权访问委托,他们可以调用调用列表中的目标——我们不希望外部用户有权访问何时引发我们的事件。
  3. 具有 AddXXXHandler 和 RemoveXXXHandler 方法的委托变量

This third option is essentially what an event gives us. When we declare an EventHandler, it gives us access to a delegate -- not publicly, not as a property, but as this thing we call an event that has just add/remove accessors.

这第三个选项本质上是事件给我们的。当我们声明一个 EventHandler 时,它让我们可以访问一个委托——不是公开的,也不是作为一个属性,而是作为一个我们称之为刚刚添加/删除访问器的事件。

Let's see what the same program looks like, but now using an Event instead of the public delegate (I've also changed our Mediator to a singleton):

让我们看看同样的程序是什么样的,但现在使用事件而不是公共委托(我也将我们的调解器更改为单例):

Example 2: With EventHandler instead of a public delegate

示例 2:使用 EventHandler 而不是公共委托

Mediator:

调解员:

class Mediator
{

    private static readonly Mediator _Instance = new Mediator();

    private Mediator() { }

    public static Mediator GetInstance()
    {
        return _Instance;
    }

    public event EventHandler<PersonChangedEventArgs> PersonChanged; //this is just a property we expose to add items to the delegate.

    public void OnPersonChanged(object sender, Person p)
    {
        var personChangedDelegate = PersonChanged as EventHandler<PersonChangedEventArgs>;
        if (personChangedDelegate != null)
        {
            personChangedDelegate(sender, new PersonChangedEventArgs() { Person = p });
        }
    }
}

Notice that if you F12 on the EventHandler, it will show you the definition is just a generic-ified delegate with the extra "sender" object:

请注意,如果您在 EventHandler 上按 F12,它将向您显示该定义只是一个带有额外“发送者”对象的泛型化委托:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The User Control:

用户控制:

public partial class DetailView : UserControl
{
    public DetailView()
    {
        InitializeComponent();
        Mediator.GetInstance().PersonChanged += DetailView_PersonChanged;
    }

    void DetailView_PersonChanged(object sender, PersonChangedEventArgs e)
    {
        BindData(e.Person);
    }

    public void BindData(Person p)
    {
        lblPersonHairColor.Text = p.HairColor;
        lblPersonId.Text = p.IdPerson.ToString();
        lblPersonName.Text = p.Name;
        lblPersonNickName.Text = p.NickName;

    }
}

Finally, here's the Form1.cs code:

最后,这里是 Form1.cs 代码:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        Mediator.GetInstance().OnPersonChanged(this, (Person)comboBox1.SelectedItem);
}

Because the EventHandler wants and EventArgs as a parameter, I created this class with just a single property in it:

因为 EventHandler 需要 EventArgs 作为参数,所以我创建了这个类,其中只有一个属性:

class PersonChangedEventArgs
{
    public Person Person { get; set; }
}

Hopefully that shows you a bit about why we have events and how they are different -- but functionally the same -- as delegates.

希望这可以向您展示我们为何举办活动以及它们与代表有何不同——但在功能上是相同的。

回答by Venkatesh Muniyandi

To define about event in simple way:

以简单的方式定义事件:

Event is a REFERENCEto a delegate with two restrictions

事件是对具有两个限制的委托的REFERENCE

  1. Cannot be invoked directly
  2. Cannot be assigned values directly (e.g eventObj = delegateMethod)
  1. 不能直接调用
  2. 不能直接赋值(例如 eventObj = delegateMethod)

Above two are the weak points for delegates and it is addressed in event. Complete code sample to show the difference in fiddler is here https://dotnetfiddle.net/5iR3fB.

以上两个是代表的弱点,它在事件中得到解决。显示 fiddler 差异的完整代码示例在这里https://dotnetfiddle.net/5iR3fB

Toggle the comment between Event and Delegate and client code that invokes/assign values to delegate to understand the difference

切换事件和委托之间的注释以及调用/分配值以委托的客户端代码以了解差异

Here is the inline code.

这是内联代码。

 /*
This is working program in Visual Studio.  It is not running in fiddler because of infinite loop in code.
This code demonstrates the difference between event and delegate
        Event is an delegate reference with two restrictions for increased protection

            1. Cannot be invoked directly
            2. Cannot assign value to delegate reference directly

Toggle between Event vs Delegate in the code by commenting/un commenting the relevant lines
*/

public class RoomTemperatureController
{
    private int _roomTemperature = 25;//Default/Starting room Temperature
    private bool _isAirConditionTurnedOn = false;//Default AC is Off
    private bool _isHeatTurnedOn = false;//Default Heat is Off
    private bool _tempSimulator = false;
    public  delegate void OnRoomTemperatureChange(int roomTemperature); //OnRoomTemperatureChange is a type of Delegate (Check next line for proof)
    // public  OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), 
    public  event OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), 

    public RoomTemperatureController()
    {
        WhenRoomTemperatureChange += InternalRoomTemperatuerHandler;
    }
    private void InternalRoomTemperatuerHandler(int roomTemp)
    {
        System.Console.WriteLine("Internal Room Temperature Handler - Mandatory to handle/ Should not be removed by external consumer of ths class: Note, if it is delegate this can be removed, if event cannot be removed");
    }

    //User cannot directly asign values to delegate (e.g. roomTempControllerObj.OnRoomTemperatureChange = delegateMethod (System will throw error)
    public bool TurnRoomTeperatureSimulator
    {
        set
        {
            _tempSimulator = value;
            if (value)
            {
                SimulateRoomTemperature(); //Turn on Simulator              
            }
        }
        get { return _tempSimulator; }
    }
    public void TurnAirCondition(bool val)
    {
        _isAirConditionTurnedOn = val;
        _isHeatTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)
        System.Console.WriteLine("Aircondition :" + _isAirConditionTurnedOn);
        System.Console.WriteLine("Heat :" + _isHeatTurnedOn);

    }
    public void TurnHeat(bool val)
    {
        _isHeatTurnedOn = val;
        _isAirConditionTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)
        System.Console.WriteLine("Aircondition :" + _isAirConditionTurnedOn);
        System.Console.WriteLine("Heat :" + _isHeatTurnedOn);

    }

    public async void SimulateRoomTemperature()
    {
        while (_tempSimulator)
        {
            if (_isAirConditionTurnedOn)
                _roomTemperature--;//Decrease Room Temperature if AC is turned On
            if (_isHeatTurnedOn)
                _roomTemperature++;//Decrease Room Temperature if AC is turned On
            System.Console.WriteLine("Temperature :" + _roomTemperature);
            if (WhenRoomTemperatureChange != null)
                WhenRoomTemperatureChange(_roomTemperature);
            System.Threading.Thread.Sleep(500);//Every second Temperature changes based on AC/Heat Status
        }
    }

}

public class MySweetHome
{
    RoomTemperatureController roomController = null;
    public MySweetHome()
    {
        roomController = new RoomTemperatureController();
        roomController.WhenRoomTemperatureChange += TurnHeatOrACBasedOnTemp;
        //roomController.WhenRoomTemperatureChange = null; //Setting NULL to delegate reference is possible where as for Event it is not possible.
        //roomController.WhenRoomTemperatureChange.DynamicInvoke();//Dynamic Invoke is possible for Delgate and not possible with Event
        roomController.SimulateRoomTemperature();
        System.Threading.Thread.Sleep(5000);
        roomController.TurnAirCondition (true);
        roomController.TurnRoomTeperatureSimulator = true;

    }
    public void TurnHeatOrACBasedOnTemp(int temp)
    {
        if (temp >= 30)
            roomController.TurnAirCondition(true);
        if (temp <= 15)
            roomController.TurnHeat(true);

    }
    public static void Main(string []args)
    {
        MySweetHome home = new MySweetHome();
    }


}

回答by Weidong Shen

Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.

委托是一个类型安全的函数指针。事件是使用委托的发布者-订阅者设计模式的实现。