I have just started to write a few business classes that are largely made up
of properties (getters and setters). For each setter I want to fire a
changed event - each event will have a unique name
e.g.
public class CBusinessObject
{
private CProperty<longm_propId;
private CProperty<stringm_propName;
public CBusinessObject()
{
m_propId = new CProperty<long>();
m_propName = new CProperty<string>();
}
public long Id
{
get
{
return m_propId.Value;
}
set
{
m_propId.Value = value;
}
}
public string Name
{
get
{
return m_propName.Value;
}
set
{
m_propName.Value = value;
}
}
public delegate void IdChangedHandler(long originalValue, long newValue);
public delegate void NameChangedHandler(string originalValue, string
newValue);
public event IdChangedHandler IdChanged;
public event NameChangedHandler NameChanged;
}
I could declare each property as a member variable of the appropriate type;
and for each setter write code that checks if the value has changed before
firing the event.
However this seems a bit repetitive (and error prone), so I came up with the
idea of using a property class. In principle this is fine, but what I would
like to do is get the property class to fire the changed event from the
setter, somehow invoking the event on the business object. Thus all
listeners to the event on the business class will recieve the appropriate
event.
The stub for my propery class is below. I have tried a number of things
including reflection and passing arround event delgates, but I have not had
any success. Any help would be much appreciated.
public class CProperty<T>
{
private T m_value;
//I suspect that I need a member variable(s) here to point to the event
in the calling class
public CProperty(/* some info from calling class */)
{
//set member variables
}
public virtual T Value
{
get
{
return m_value;
}
set
{
if (value.Equals(m_value) == false)
{
FireValueChangedEvent(m_value, value);
}
m_value = value;
}
}
private void FireValueChangedEvent(T originalValue, T newValue)
{
//What should I do here?
}
}