C#如果某个项目引发事件,则从列表中删除该项目

本文关键字:项目 列表 删除 事件 如果 | 更新日期: 2023-09-27 17:58:00

以下是我现在拥有的:

class MyClass
{
    public string status;
    private void DoSomething()
    {
        // do something and make change to this.status;
    }
}
class MyClass2
{
    public List<MyClass> MyClassLst;
    private void DetectChangeInList()
    {
        // if the status property of an item in this.MyClassLst changed, remove this item from list
    }
}

我有一个List<MyClass>,每个MyClass都会做一些工作并更改属性status。我想检测MyClass中是否有任何一个的status发生了更改,并从MyClassLst中删除此项。

我读到一些关于活动的内容,但不太清楚如何使其发挥作用。

C#如果某个项目引发事件,则从列表中删除该项目

如果需要通知您每个MyClass实例的各个属性的更改,这不是可以神奇地发生的事情。

您的MyClass必须负责在发生更改时触发事件(通常是PropertyChanged事件,即INotifyPropertyChanged接口),而另一个类必须为列表中的每个项附加一个处理程序才能收到通知。

C#6有一些语法改进,可以稍微简化这一点,但对于每个属性仍有很多工作要做:

public class Model : INotifyPropertyChanged
{
    // this is the event which gets fired
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    // you need to raise the event in each property's setter
    private _someValue;
    public string SomeValue
    {
        get { return _someValue; }
        set { if (value != _someValue) { _someValue = value; OnPropertyChanged(); } }
    }
    private _anotherVal;
    public string AnotherValue
    {
        get { return _anotherVal; }
        set { if (value != _anotherVal) { _anotherVal = value; OnPropertyChanged(); } }
    }
}

在你的情况下,它将是:

public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    // Never use public fields! 
    // Status should be a property which gets and sets
    // the actual private backing field (_status).
    private _status;
    public string Status
    {
        get { return _status; }
        set { if (value != _status) { _status = value; OnPropertyChanged(); } }
    }
}

您很可能还想将List<MyClass>更改为您自己的ICollection<T>实现,该实现将在添加或删除项时附加和分离这些处理程序。它通常是通过从Collection<T>派生并覆盖相关方法来完成的。如果您对此感到不舒服,一种稍微简单一点的方法可能是将列表设为私有,并公开Add/Remove以及将附加/分离到PropertyChanged事件的类似方法。