[英]Change data in Class when List<sub-class> data is changed
I have a class STimer that has a List in it. 我有一个STimer类,其中有一个List。 The serviceDetail is monitored on a timer very often, and rarely changes, but when it does change I want to get the fact that the data changed without looping through the list due to processing power. serviceDetail经常在计时器上监视,并且很少更改,但是当它更改时,我想得到这样一个事实,即由于处理能力的原因,数据已更改而没有遍历列表。 Maybe this is a duplicate question that I just don't know how to search for it, but I have been trying. 也许这是一个重复的问题,我只是不知道如何搜索,但是我一直在尝试。 Here is a code Sample: 这是一个代码示例:
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;
}
I could do a .Find on the list to return all of the _serviceMonitors._runningStateChanged=true, but that seems like a lot of work parsing the List every time the timer fires, when likely only 1 out of 1,000 loops will actually have a change. 我可以在列表上执行.Find来返回所有_serviceMonitors._runningStateChanged = true,但是每次计时器触发时,解析列表的工作量似乎很大,而实际上每1,000个循环中只有1个会发生变化。
Is this even possible, or do I need to move the check for changes out of the class? 这是否有可能,还是我需要将更改检查移出课堂?
You could get this by adding an event to your ServiceDetail class 您可以通过在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 -->
}
}
}
}
And define your ListChangedEventArgs class like this 并像这样定义您的ListChangedEventArgs类
public class ListChangedEventArgs:EventArgs
{
public ServiceDetail serviceDetail { get; set; }
public ListChangedEventArgs(ServiceDetail s)
{
serviceDetail = s;
}
}
And then register to the event for each servicedetail added to the list 然后为添加到列表中的每个服务详细信息注册事件
s.ListChanged += (sender, args) => YourFunction();
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.