2011-01-24 133 views
3

我有點不確定如何說這個問題,所以請原諒我,如果這是重複的。修改時間戳更新對類屬性的任何更改

基本上我想調用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(); 
    } 
} 

回答

2

您所描述的內容聽起來非常接近通常通過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"); 
     } 
    } 
    } 
} 

這種做法將使變更通知提供給消費者類的爲好,如果這就是你可能拍攝的是什麼,不同的解決方案將是可取的。

1

不知道這是最好的方式,但你可以做到這一點的一種方法是,請致電您的屬性這三個制定者的UpdateModifiedTimeStamp()方法。

例如:

public string _firstName; 
public string Firstname 
{ 
    get { return this._firstName; } 
    set 
    { 
    this._firstName = value; 
    this.UpdateModifiedTimestamp(); 
    } 
} 

同樣,做Lastname相同,並且Phone性能爲好。

+0

這就是我試圖避免的。認爲有一個更乾淨的方式來做到這一點。 – 2011-01-24 00:50:36

+0

@J。 Mitchell:除了使用@ BrokenGlass的回答建議的INotifyPropertyChanged外,這是我知道的唯一方法。我想知道是否還有更乾淨的方法。 – VoodooChild 2011-01-24 01:07:30