I'm a bit unsure on how I'd word this question, so pardon me if this is duplicate.
Basically I want to call UpdateModifiedTimestamp everytime a property is changed. This is just a sample class I wrote up pretty quickly, but should explain what I'm trying to achieve.
Everytime Firstname, Lastname, or Phone is changed it should update the ModifiedOn property.
public class Student {
public DateTime ModifiedOn { get; private set; }
public readonly DateTime CreatedOn;
public string Firstname { set; get; }
public string Lastname { set; get; }
public string Phone { set; get; }
public Student() {
this.CreatedOn = DateTime.Now();
}
p开发者_如何学Crivate void UpdateModifiedTimestamp() {
this.ModifiedOn = DateTime.Now();
}
}
What you are describing sounds pretty close to the property change notification usually done via the INotifyPropertyChanged
interface. Implementing this interface would give you a little more generic solution to your problem:
public class Student :INotifyPropertyChanged
{
public string Firstname { set; get; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
UpdateModifiedTimestamp(); // update the timestamp
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
string _firstname;
public string Firstname //same for other properties
{
get
{
return _firstname;
}
set
{
if (value != _firstname)
{
_firstname = value;
NotifyPropertyChanged("Firstname");
}
}
}
}
This approach would make the change notification available to consumers of your class as well, if that's what you are shooting for, a different solution probably would be preferable.
Not sure if this is the best way, but one way you could do this is, call the UpdateModifiedTimeStamp()
method in the three setters of your properties.
eg:
public string _firstName;
public string Firstname
{
get { return this._firstName; }
set
{
this._firstName = value;
this.UpdateModifiedTimestamp();
}
}
Similarly, do the same for Lastname
, and Phone
properties as well.
精彩评论