类/方法/接口的事件

本文关键字:事件 方法 接口 | 更新日期: 2023-09-27 18:35:45

如果我的属性在 myVariable 类中发生了更改,我会尝试创建一个自定义事件,但是在每个示例中,我必须为每个值执行此操作。无法在写入接口或方法上触发吗?

属性类

public sealed class LogEntry
{
    public DateTime TimeStamp { get; set; }
    public int Pid { get; set; }
    public int Tid { get; set; }
    public string ProcessName { get; set; }
    public string Tag { get; set; }
    public string Message { get; set; }
}

我的界面

public interface ILogObserver
{
    void NewEntry(LogEntry entry);
    void NewData(string[] data, int size);
}
如果

调用这两种方法之一,如果数据已更改,我想触发事件。有人可以支持我吗?

类/方法/接口的事件

您可以尝试为此使用现有接口 - INotifyPropertyChanged .这是MSDN关于它的帖子。

下面是使用此接口的预览版,有关完整示例,请参阅链接。

// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerNameValue = String.Empty;
    private string phoneNumberValue = String.Empty;
    public event PropertyChangedEventHandler PropertyChanged;
    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerNameValue = "Customer";
        phoneNumberValue = "(312)555-0100";
    }
    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }
    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }
    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }
        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged();
            }
        }
    }
    public string PhoneNumber
    {
        get
        {
            return this.phoneNumberValue;
        }
        set
        {
            if (value != this.phoneNumberValue)
            {
                this.phoneNumberValue = value;
                NotifyPropertyChanged();
            }
        }
    }
}