脏检查的对象?对象

2023-09-03 15:35:06 作者:爱你%~百分百

考虑以下对象:

 公共类Foo
   暗淡m_SomePropertyInFoo作为字符串

    公共财产SomePropertyInFoo作为字符串
    得到
        返回m_SomePropertyInFoo
    最终得到
    设置(值作为字符串)
        m_SomePropertyInFoo =价值
    最终设置
端类
 

我要确定何时 SomePropertyInFoo 具有有资格的的实例作为脏的一个新值。这里是渔获:我不希望有打电话给在每个二传手一些功能,因为我不想让开发者有执行code每次(因为他们犯了一个错误,并错过任何一个属性)。

解决方案   

下面是渔获:我不希望有调用一些功能在每个二传,因为我不想让开发者有执行code每次(因为他们犯了一个错误,并错过属性)。

监察对象的介绍

有两种选择,我可以看到。

如果您的类型实现 INotifyPropertyChanged的,您可以订阅对象的的PropertyChanged 事件,并用它来追踪变化

否则,如果要实现这个的没有改变属性的code 的,外部变化的跟踪将需要。也许你认为使用反射的方法(或潜在 PropertyDescriptors )抓住每个属性的值,随后,比较它的当前值,以确定是否该对象是脏。这不是一种廉价的操作,然而

另外,潜在的更优雅,选择是使用面向方面编程添加在code在编译时会自动每个属性。 PostSharp 可以作出来处理这个很容易,例如。

Consider the following object:

Public Class Foo
   dim m_SomePropertyInFoo as string

    public property SomePropertyInFoo as string
    get
        return m_SomePropertyInFoo
    end get
    set(value as string)
        m_SomePropertyInFoo = value
    end set
end Class

I want to determine when SomePropertyInFoo has a new value which would qualify the instance of Foo as dirty. Here is the catch: I don't want to have to call some function in each setter because I don't want the devs to have to implement code each time(because they could make a mistake and miss a property).

解决方案

Here is the catch: I don't want to have to call some function in each setter because I don't want the devs to have to implement code each time(because they could make a mistake and miss a property).

There are two options I could see.

If your type implements INotifyPropertyChanged, you could subscribe to the object's PropertyChanged event and use this to track for changes.

Otherwise, if you want to implement this with no changes to the code of the properties, external change tracking would be required. You could make a method that used Reflection (or potentially PropertyDescriptors) to grab the value of each property, and later, compare it to the current values to determine if that object is "dirty". This is not an inexpensive operation, however.

Another, potentially more elegant, option would be to use Aspect Oriented Programming to add the code to each property automatically at compile time. PostSharp could be made to handle this fairly easily, for example.