修改时间戳会更新类属性的任何更改
我有点不确定如何表达这个问题,所以如果这是重复的,请原谅我。
基本上我想在每次更改属性时调用 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();
}
}
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();
}
private void UpdateModifiedTimestamp() {
this.ModifiedOn = DateTime.Now();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所描述的内容听起来非常接近通常通过
INotifyPropertyChanged
接口。实现这个接口将为您的问题提供更通用的解决方案:这种方法也将使更改通知可供您的类的使用者使用,如果这就是您的目标,那么不同的解决方案可能会更好。
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: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.
不确定这是否是最好的方法,但可以执行此操作的一种方法是,在属性的三个设置器中调用
UpdateModifiedTimeStamp()
方法。例如:
同样,对
Lastname
和Phone
属性也执行相同的操作。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:
Similarly, do the same for
Lastname
, andPhone
properties as well.