如果分配器分配了相同的值,它应该立即返回吗? [英] Should a setter return immediately if assigned the same value?

查看:79
本文介绍了如果分配器分配了相同的值,它应该立即返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现INotifyPropertyChanged的类中,我经常看到这种模式:

In classes that implement INotifyPropertyChanged I often see this pattern :

    public string FirstName
    {
        get { return _customer.FirstName; }
        set
        {
            if (value == _customer.FirstName)
                return;

            _customer.FirstName = value;

            base.OnPropertyChanged("FirstName");
        }
    }

精确的线条

            if (value == _customer.FirstName)
                return;

困扰着我.我经常这样做,但是我不确定它是否必要.毕竟,如果调用者分配了相同的值,则我不想重新分配该字段,尤其是,通知我的订阅者该属性已更改的时间在语义上并未更改.

are bothering me. I've often did this but I am not that sure it's needed nor good. After all if a caller assigns the very same value I don't want to reassign the field and, especially, notify my subscribers that the property has changed when, semantically it didn't.

除了通过释放UI来更新屏幕上可能看起来相同的东西来节省一些CPU/RAM/etc/whatever_medium,我们可以获得什么?

Except saving some CPU/RAM/etc by freeing the UI from updating something that will probably look the same on the screen/whatever_medium what do we obtain?

有些人可以通过在属性上重新分配相同的值来强制刷新(但这不是一种好的做法)吗?

Could some people force a refresh by reassigning the same value on a property (NOT THAT THIS WOULD BE A GOOD PRACTICE HOWEVER)?

1.我们应该这样做还是应该这样做?

2.为什么?

推荐答案

是的,当使用者设置的属性值等于已经保留的值时,应该立即返回.

Yes, you should return immediately when the consumer is setting a property value that is equal to the value which is already being persisted.

首先,没有理由浪费任何时间或资源在属性的设置器中-该值已经设置,因此不需要采取进一步的措施.同样,如果存储在属性的后备字段中的值没有更改,则永远不要调用OnPropertyChanged-该方法旨在在更改了 值时引发,而不是在调用属性的setter时引发.

First of all, there is no reason to waste any time or resources in the setter of the property - the value is already set so no further action is needed. Also you should never call OnPropertyChanged if the value stored in the property's backing field hasn't changed - the method is intended to be raised when the value has changed not when the property's setter has been called.

所有这些,但是-如果设置者没有对OnPropertyChanged的调用,我就不会费心先检查该值.对于仅设置后备字段值而没有其他设置的简单setter方法,实际上总是始终设置值而不是先检查然后设置值会更快.仅当属性的设置方法具有不应触发或可能导致不必要的性能损失的附加逻辑时,才使用此模式.

All that being said, however - if the setter didn't have a call to OnPropertyChanged I wouldn't have bothered to check the value first. In the case of a simple setter that only sets the backing field's value and nothing else it is actually going to be faster to always the set the value rather than checking first then setting the value. Only use this pattern when the property's setter has additional logic that either shouldn't fire or may incur an unnecessary performance penalty.

这篇关于如果分配器分配了相同的值,它应该立即返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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