首页 / 知识

关于c#:代表和活动之间有什么区别?

2023-04-13 07:16:00

What are the differences between delegates and events?

代表和活动之间有什么区别? 两者都不能保存对可以执行的函数的引用吗?


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


要了解这些差异,您可以看看这2个示例

代表示例(在本例中为Action - 这是一种不返回值的委托)

1
2
3
4
5
6
7
8
9
10
11
12
public class Animal
{
    public Action Run {get; set;}

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

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

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

这段代码运作良好,但你可能会有一些弱点。

例如,如果我写这个:

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

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

另一个弱点是每个使用Animal类的类都可以提升RaiseEvent只是调用它animal.RaiseEvent()

要避免这些弱点,可以在c#中使用events

您的Animal类将以这种方式更改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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"));
    }
}

召唤事件

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

区别:

  • 您没有使用公共属性,而是使用公共字段(使用事件,编译器保护您的字段免受不必要的访问)
  • 无法直接分配事件。在这种情况下,它不会引起我在覆盖行为时显示的先前错误。
  • 班上没有人可以提出这个活动。
  • 事件可以包含在接口声明中,而字段则不能
  • 笔记:

    EventHandler被声明为以下委托:

    1
    public delegate void EventHandler (object sender, EventArgs e)

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

    此示例使用EventHandler,也可以使用EventHandler编写。

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


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

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

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

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


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

    简而言之,从文章中删除 - 事件是对代表的封装。

    文章引用:

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

  • A public delegate variable

  • A delegate variable backed by a property

  • 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#5.0 Unleashed,请阅读第18章"事件"中的"对代理人的简单使用的限制",以更好地理解两者之间的差异。

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

    示例1:使用公共委托

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

    enter image description here

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

    • Mediator.cs - 静态类保存委托
    • Form1.cs - 主要形式
    • DetailView.cs - 用户控件显示所有细节

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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);
            }
        }
    }

    这是我们的用户控件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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;

        }
    }

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

    1
    2
    3
    4
    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`.
    }

    好。这就是如何在不使用事件和仅使用委托的情况下使其工作。我们只是将一个公共委托放入一个类 - 你可以使它成为静态或单个,或者其他什么。大。

    但是,但是,我们不想做我刚才描述的事情。因为公共领域对许多人来说是坏事,很多原因。那么我们有什么选择呢?正如John Skeet所描述的,以下是我们的选择:

  • 一个公共委托变量(这是我们上面刚刚做过的。不要这样做。我刚才告诉你为什么它很糟糕)
  • 将委托放入带有get / set的属性中(这里的问题是订阅者可以互相覆盖 - 所以我们可以向委托订阅一堆方法然后我们可能会意外地说PersonChangedDel = null,消除所有其他这里剩下的另一个问题是,由于用户可以访问委托,因此他们可以调用调用列表中的目标 - 我们不希望外部用户有权访问何时提升我们的事件。
  • 具有AddXXXHandler和RemoveXXXHandler方法的委托变量
  • 第三种选择基本上是一个事件给我们的东西。当我们声明一个EventHandler时,它允许我们访问一个委托 - 不是公开的,不是作为属性,但是我们称之为只添加/删除访问者的事件。

    让我们看看相同的程序是什么样的,但现在使用Event代替公共委托(我还将我们的Mediator更改为单例):

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

    中保

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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 });
            }
        }
    }

    请注意,如果您在EventHandler上使用F12,它将向您显示定义只是一个带有额外"sender"对象的通用ified委托:

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

    用户控制:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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;

        }
    }

    最后,这是Form1.cs代码:

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

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

    1
    2
    3
    4
    class PersonChangedEventArgs
    {
        public Person Person { get; set; }
    }

    希望这能告诉你为什么我们有事件以及它们如何不同 - 但在功能上与代表一样。


    事件和代表之间的误会真是太棒了!委托指定TYPE(例如classinterface),而事件只是一种成员(例如字段,属性等)。并且,就像任何其他类型的成员一样,事件也有类型。但是,在事件的情况下,事件的类型必须由委托指定。例如,您不能声明由接口定义的类型的事件。

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

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

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


    您还可以在接口声明中使用事件,而不是代理人使用事件。


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

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


    以简单的方式定义事件:

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

  • 无法直接调用
  • 无法直接赋值(例如eventObj = delegateMethod)
  • 以上两个是代表们的弱点,并在事件中得到解决。完整的代码示例以显示fiddler的不同之处在于https://dotnetfiddle.net/5iR3fB。

    切换Event和Delegate之间的注释以及调用/赋值给委托的客户端代码以理解差异

    这是内联代码。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
     /*
    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();
        }


    }

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


    CovarianceContravariance为委托对象提供了额外的灵活性。另一方面,事件没有这样的概念。

    • Covariance允许您将方法分配给代理所在的位置
      方法的返回类型是从类派生的类
      指定委托的返回类型。
    • Contravariance允许您为委托分配方法
      方法的参数类型是类的基类
      指定为委托的参数。


    委托调用函数引用

    最新内容

    相关内容

    热门文章

    推荐文章

    标签云

    猜你喜欢