我有点不确定我该如何表达这个问题,所以请原谅我是否重复。
基本上我想在每次更改属性时调用 UpdateModifiedTimestamp。这只是我很快编写的示例类,但应该可以解释我想要实现的目标。
每次更改名字、姓氏或电话时,都应更新 ModifiedOn 属性。
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();
}
private void UpdateModifiedTimestamp() {
this.ModifiedOn = DateTime.Now();
}
}
最佳答案
您所描述的内容听起来非常接近通常通过 INotifyPropertyChanged
完成的属性更改通知。界面。实现此接口(interface)将为您提供更通用的问题解决方案:
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");
}
}
}
}
这种方法也可以让您的类的消费者可以使用更改通知,如果这是您的目标,则可能更可取不同的解决方案。
关于c# - Modified On Timestamp 根据类属性的任何更改更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4777526/