更改List <子类>数据时更改Class中的数据

时间:2016-05-19 16:53:09

标签: c# inner-classes

我有一个类STimer,里面有一个List。 serviceDetail经常在一个计时器上监视,并且很少更改,但是当它确实发生更改时,我希望得到这样的事实:由于处理能力,数据在没有循环遍历列表的情况下发生了变化。也许这是一个重复的问题,我不知道如何搜索它,但我一直在努力。这是代码示例:

class STimers
{

public class ServiceDetail
    {
        private int _serviceKey;
        private bool _isRunning = true;
        private bool _runningStateChanged = false;

        public bool isRunning
        {
            get { return _isRunning; }
            set
            {
                //Check to see if the data is the same, if so, don't change, if not, change and flag as changed
                if(_isRunning = value) { return; }
                else
                {
                    _isRunning = value;
                    _runningStateChanged = true;
        <-- Update STimers._dataChanged to true -->
                }
            }
        }

    }


public List<ServiceDetail> _serviceMonitors = new List<ServiceDetail>();
public bool _dataChanged = false;


}

我可以在列表上执行.Find以返回所有_serviceMonitors._runningStateChanged = true,但是每次定时器触发时,这似乎需要解析List,而实际上只有1个实际上只有1个循环有变化。

这是否可能,或者我是否需要将检查结果移出课堂?

1 个答案:

答案 0 :(得分:0)

您可以通过向ServiceDetail类

添加事件来实现此目的
public class ServiceDetail
{
    public event EventHandler<ListChangedEventArgs> ListChanged;
    private int _serviceKey;
    private bool _isRunning = true;
    private bool _runningStateChanged = false;

    private void OnListChanged(ListChangedEventArgs e){
        if (ListChanged != null) ListChanged(this, e);
    }       

    public bool isRunning
    {
        get { return _isRunning; }
        set
        {
            //Check to see if the data is the same, if so, don't change, if not, change and flag as changed
            if(_isRunning = value) { return; }
            else
            {
                _isRunning = value;
                _runningStateChanged = true;
                OnListChanged(new ListChangedEventArgs(this));
    <-- Update STimers._dataChanged to true -->
            }
        }
    }

}

并像这样定义 ListChangedEventArgs

public class ListChangedEventArgs:EventArgs
{
    public ServiceDetail serviceDetail { get; set; }
    public ListChangedEventArgs(ServiceDetail s)
    {
        serviceDetail = s;
    }
}

然后为添加到列表中的每个servicedetail注册事件

s.ListChanged += (sender, args) => YourFunction();

希望有所帮助