委托,为什么关键字事件要使用运算符“=”?

3
我知道与委托变量相关的关键字“event”只允许您使用运算符+ =和- =,而运算符=是被禁止的。我试图验证这种行为,但在mydelegate = p.stampaPropUmano;这一行,不仅Visual Studio没有提示错误,而且所有内容都运行得完美无缺。stampaPropUmano和stampaPropAnimale分别是类Umano和Animale的两个方法。
您知道原因吗?如果关键字“event”具有其他属性,请告诉我。在我的文档中,我只找到了我之前说过的属性。谢谢!
namespace csharpWPFevent
    { 
    public delegate void delegato(int index=7);

public partial class MainWindow : Window
    {
        public event delegato mydelegate;

        public MainWindow()
        {
            InitializeComponent();
            Persona p = new Persona();
            p.Costa = "Paulo";
            p.Cognome = "Sousa";
            Animale a = new Animale("Fufficus", "Cane spaziale");

            mydelegate = p.stampaPropUmano; // ??????? Why?
            mydelegate += a.stampaPropAnimale;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            mydelegate(1);   
        }
    }
}
3个回答

4

这个限制是针对声明了event的类的客户端的,而该类本身可以使用=。例如:

public delegate void delegato(int index=7);

public class Foo
{
    public event delegato myEvent;

    public void Bar()
    {
        // no error
        myEvent = (int i) => {};
    }
}

void Main()
{
    var foo = new Foo();
    // The event 'Foo.myEvent' can only appear on the left hand side of += or -= (except when used from within the type 'Foo')
    foo.myEvent = (int i) => {};        
}

3

C#事件是一种多路广播委托,即具有多个目标的委托。

event关键字的作用仅在于确保不拥有该委托的类只能在字段上使用+=-=运算符。

通过使用=运算符,您将覆盖delegate的值,并将其分配给p.stampaPropUmano


1
委托:
委托:
   Action a = null;
   a = MyMethod;  // overwrites value of a with one method;
   a += MyMethod; // assigns method to a (not changing anything apart of it)
   a -= MyMethod; // removes method from a
事件:

类声明内部:

   public event Action MyEvent;

在类的构造函数或任何其他方法中:
   MyEvent = new Action(MyMethod);  // assign the event with some delegate;

在同一个或任何其他类中:

   myClassInstance.MyEvent += new Action(MyOtherMethod); // subscribing for the event;
   myClassInstance.MyEvent -= new Action(MyOtherMethod); // unsubscribing for the event;      

所以,每当事件被触发时,它会调用订阅了它的委托中的方法(或方法),或者在创建此事件的类内部显式设置。

你可能会问:为什么不直接从其他类给事件赋值?

因为在这种情况下使用事件是不安全的。

假设可以从其他类分配一些值来表示事件,并考虑以下场景:

Class A has event - > MyEvent;

Class B subscribes for event with += 
Class C subscribes for event with += 
Class D changes MyEvent value to `null`

Event is invoked in Class A, but it's set to null and exception is thrown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接