簡體   English   中英

通過CLR書在C#中輸入錯誤的代碼

[英]Wrong Code In C# Via CLR Book

我正在讀這本書,並停留在這里:

public static class EventArgExtensions { 
   public static void Raise<TEventArgs>(this TEventArgs e,  
      Object sender, ref EventHandler<TEventArgs> eventDelegate)  
      where TEventArgs : EventArgs { 

      // Copy a reference to the delegate field now into a temporary field for thread safety  
      EventHandler<TEventArgs> temp =  
         Interlocked.CompareExchange(ref eventDelegate, null, null); 

      // If any methods registered interest with our event, notify them   
      if (temp ! = null) temp(sender, e); 
   } 
}

具體來說,MSDN文檔說

 public static object CompareExchange(ref object location1, object value, object comparand) 

System.Threading.Interlocked的成員

摘要:
比較兩個對象是否相等,如果相等,則替換其中一個對象。

參數:
location1 :與比較對象進行比較並可能被替換的目標對象。
value :如果比較結果相等,則將替換目標對象的對象。
比較對象:與location1處的對象進行比較的對象。

返回值:
location1中的原始值。

例外情況:
System.ArgumentNullException:location1的地址為空指針。

這意味着這是錯誤的:

 EventHandler<TEventArgs> temp =  
             Interlocked.CompareExchange(ref eventDelegate, null, null); 

          // If any methods registered interest with our event, notify them   
          if (temp ! = null) temp(sender, e); 

因為我需要檢查傳遞給CompareExchange的內容,而不是輸出。

我想念什么嗎?

不,代碼很好。 它實際上只是執行易失性讀取的一種方式。 如果將null替換為null,即eventDelegate為null,則它將僅返回null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM