首頁 > 後端開發 > C++ > 如何在 C# 中屬性值變更時引發自訂事件?

如何在 C# 中屬性值變更時引發自訂事件?

Linda Hamilton
發布: 2025-01-01 01:16:10
原創
988 人瀏覽過

How to Raise a Custom Event When a Property Value Changes in C#?

如何在屬性值更改時引發事件

您想要一個名為ImageFullPath1 的屬性每當其值發生變化時引發一個事件。雖然您知道使用 INotifyPropertyChanged 接口,但您更喜歡利用事件來實現此目的。

INotifyPropertyChanged 介面其實是透過事件實現的。它有一個成員,PropertyChanged,這是一個可以由消費者訂閱的事件。

安全實作:

以下程式碼片段示範了 INotifyPropertyChanged介面的安全實現,以及特定屬性的附加事件(ImageFullPath):

public class MyClass : INotifyPropertyChanged
{
    private string imageFullPath;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged("ImageFullPath");
            }
        }
    }

    protected void OnImageFullPathChanged(EventArgs e)
    {
        EventHandler handler = ImageFullPathChanged;
        if (handler != null)
            handler(this, e);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public event EventHandler ImageFullPathChanged;
}
登入後複製

此實現確保以下內容:

  • 抽象屬性變更通知方法,以便輕鬆應用於其他屬性
  • 複製PropertyChanged委託在呼叫它之前避免競爭條件
  • 正確實作INotifyPropertyChanged 介面

.NET 4.5 中的CallerMM完成>

。 🎜>對於.NET 4.5及更高版本,

CallerMemberAttribute可用於消除硬編碼字串原始碼中的屬性名稱:

以上是如何在 C# 中屬性值變更時引發自訂事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板