public abstract class ANetworkedComponent
{
public bool Dirty { get; set; } = false;
}
public class Collider: ANetworkedComponent
{
public Vector2 Velocity { get; set; }
}
I need to set Dirty
to true
every time a property of a class that inherits from ANetworkedComponent
is modified. For example, when
var collider = new Collider();
collider.Velocity = new Vector(10, 10);
is executed, then collider.Dirty should be set to true
.
Modifying the properties manually is not an option because there are too many properties and it's not DRY
. Are there other options?
CodePudding user response:
It only looks like a DRY violation because you only have one Dirty
Property for the whole class. If you had a separate IsPropertyDirty
for each property, you wouldn't say that was a DRY violation.
The fastest (execution time-wise), is going to be properties you write yourself. But as you have noted, it is the most developer time consuming, so I would only do that if performance profiling indicates it.
Another quick option would be "Aspect Oriented Programming". There are libraries for C#, like PostSharp, that allow you to add 'aspects' to classes. For example, you could have PostSharp auto-implement INotifyPropertyChanged
on your classes for you, which you could then use to listen for property changes and set Dirty
. I'm sure you can also add your own aspect to change the Dirty state under various conditions.
PostSharp is in a class of AOP libraries that weaves code into your assemblies during compilation. Typically you decorate classes, properties, and methods with attributes and that tells PostSharp what behaviors to implement automatically in your code. There are also libraries that support runtime aspects (many IOC containers support this), and although performance won't match those of a code generated AOP, they are quite serviceable.
CodePudding user response:
You could create a generic property with a virtual field inside that uses reflection to change the Dirty flag on the set of that inner property