gpt4 book ai didi

c# - C# 中的错误代码通过 CLR 书

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:16 25 4
gpt4 key购买 nike

我正在读这本书并被困在这里:

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)

Member of System.Threading.Interlocked

Summary:
Compares two objects for reference equality and, if they are equal, replaces one of the objects.

Parameters:
location1: The destination object that is compared with comparand and possibly replaced.
value: The object that replaces the destination object if the comparison results in equality.
comparand: The object that is compared to the object at location1.

Returns:
The original value in location1.

Exceptions:
System.ArgumentNullException: The address of location1 is a null pointer.



这意味着这是错误的:
 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 而不是输出。

我错过了什么吗?

最佳答案

不,代码很好。它实际上只是一种执行 volatile 读取的方式。只有将 null 替换为 null 时才会返回 null - 即如果 eventDelegate一片空白。

关于c# - C# 中的错误代码通过 CLR 书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2930005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com