我不太确定如何表达这个问题,请原谅。

基本上,我想每次更改属性时都调用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界面完成的属性更改通知。实现此接口将为您提供一些通用的解决方案:

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# - 修改时间戳记后,对类属性的任何更改都会更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4777526/

10-11 20:19
查看更多