事件处理程序和空条件运算符 [英] Event handler and null-conditional operator

查看:75
本文介绍了事件处理程序和空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,实现 INotifyPropertyChanged 接口:

 公共事件PropertyChangedEventHandler PropertyChanged;私人无效OnPropertyChanged([CallerMemberName]字符串propertyName = null){var handler = PropertyChanged;如果(处理程序!= null)handler.Invoke(this,new PropertyChangedEventArgs(propertyName));} 

两件事:

  1. 将事件复制到本地变量以防止多线程错误(

    1. 检查它是否为null,以防止 NullReferenceException

    但是现在,我们可以使用?.运算符进行null检查.如果我使用它,Resharper处于闲置状态:

    因此,问题是:如果我使用空条件运算符,是否应该将事件 ProperyChanged 复制到局部变量?

    解决方案

    如果我使用空条件运算符,应该将事件ProperyChanged复制到本地变量吗?

    不,没有必要.实际上,引入空条件运算符的主要原因之一是使用此模式简化了代码.它与将源值复制到局部变量具有相同的效果,并从本质上避免了复制到局部变量"技术旨在解决的检查并使用"并发陷阱.

    查看相关文章:
    调用事件,h(args)与EventName?.Invoke()(几乎完全是重复的…它确实从一个略微的角度解决了这个问题虽然有不同的角度)
    为什么在调用自定义事件之前应该检查null?
    使用扩展方法引发C#事件-不好吗?
    在引发事件之前是否有任何理由将事件分配给局部变量?

    For example, implement INotifyPropertyChanged interface:

    public event PropertyChangedEventHandler PropertyChanged;
    
    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    

    Two things:

    1. Copy event to local variable to prevent errors with multithreading (here are some examples). Resharper gives notification, if you don't copy to local variable:

    1. Check it for null, to prevent NullReferenceException

    But now, we can use ?. operator for null-checking. And if I use it, Resharper is idle:

    So, question is: should I copy event ProperyChanged to local variable, if I use null-conditional operator?

    解决方案

    should I copy event ProperyChanged to local variable, if I use null-conditional operator?

    No, there's no need. In fact, one of the main reasons the null-conditional operator was introduced was to simplify code using this pattern. It has the same effect as copying the source value to a local variable and inherently avoids the "check and use" concurrency trap that the "copy to local variable" technique is intended to address.

    See related posts:
    Invoking Events, h(args) vs EventName?.Invoke() (almost an exact duplicate…it does approach the question from a slightly different angle though)
    Why should I check for null before I invoke the custom event?
    Raising C# events with an extension method - is it bad?
    Is there any reason to assign an event to a local variable before raising it?

    这篇关于事件处理程序和空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆