Dirty Checking for an object?
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 = val开发者_运维技巧ue
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).
One option is using a runtime proxy like Castle DynamicProxy
http://www.castleproject.org/services/index.html
Here is a blog post that shows "Tracking dirtiness with DynamicProxy"
http://mookid.dk/oncode/archives/8
Couple of options if you do not want to re-code each property.
Consider using a framework that can be used to weave code into you class automatically that can implement change tracking e.g. PostSharp.
Serialize the instance when you first retrieve it, serialize it at the point you save it and do a compare of the bytes.
1 is preferable, whereas 2 is cheap and nasty perhaps.
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.
Set m_SomePropertyInFoo to null (Nothing in VB) initially. Then, when you want to check whether a value has been set, check whether it's null.
You'll have to adjust the setter to return String.Empty if the value is null, otherwise you'll have to handle NullReference exceptions in the next layer up, which is no fun. My VB is a little rusty, but here goes:
dim m_SomePropertyInFoo as string = Nothing
public property SomePropertyInFoo as string
get
If m_SomePropertyInFoo Is Nothing Then
return string.Empty
Else
return m_SomePropertyInFoo
End If
end get
set(value as string)
m_SomePropertyInFoo = value
end set
精彩评论