2015-09-08 17 views
3

我知道與委託變量關聯的關鍵字'event'允許您只使用運算符+ =和 - =,並且運算符=被禁止。我試圖驗證這種行爲,但在行mydelegate = p.stampaPropUmano;不僅Visual Studio不會給我一個錯誤,但也都完美的作品。 stampaPropUmano和stampaPropAnimale分別是Umano和Animale類的兩種方法。代表,關鍵詞事件爲什麼與運算符'='一起使用?

你知道原因嗎?請讓我知道關鍵字「事件」是否給出了其他屬性..在我的文檔中,我發現了我之前說過的屬性。問候

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

回答

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是一個多播委託。也就是說,具有多個目標的代表。

所有event關鍵字的作用是確保不擁有代表在現場只能使用+=-=運營商類。

通過使用=運算符,您將覆蓋delegato的值,並將其賦值給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 
相關問題