c# - 检查委托(delegate)是否为空

标签 c# .net delegates

我正在阅读 Essential C# 3.0 一书,想知道这是否是检查委托(delegate)是否为 null 的好方法?:

class Thermostat
{
    public delegate void TemperatureChangeHandler ( float newTemperature );

    public TemperatureChangeHandler OnTemperatureChange { get; set; }

    float currentTemperature;

    public float CurrentTemperature
    {
        get { return this.currentTemperature; }
        set
        {
            if ( currentTemperature != value )
            {
                currentTemperature = value;

                TemperatureChangeHandler handler = OnTemperatureChange;

                if ( handler != null )
                {
                    handler ( value );
                }
            }
        }
    }
}

如果类型不可变,解决方案会改变吗?我想也许有了不变性,您就不会遇到这个线程问题。

最佳答案

对条件访问使用问号:

OnTemperatureChange?.Invoke();

关于c# - 检查委托(delegate)是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/972932/

相关文章:

c# - Controller 映射中的 ASP.NET MVC 枚举参数

c# - 找出 linq 完成了多少次迭代

c# - 以多线程方式使用 BeginInvoke/EndInvoke。 AsyncCallback、AsyncWaitHandle 和 IsCompleted 如何交互?

c# xml 序列化分组子节点中的元素

c# 事件处理程序被添加两次

c# - 替换 .net 中的标准异常/错误表单

c# - Entity Framework 6 中的一对多关系

c# - 当 DateTime 传递给采用 Nullable DateTime 的方法时,为什么我会丢失 DateTime 的毫秒数?

c# - 循环中的匿名 c# 委托(delegate)

delegates - 为什么以编程方式选择 tabbarController 索引不会调用委托(delegate)方法