【发布时间】:2014-03-02 23:26:59
【问题描述】:
我无法让“foreach”功能正常工作。 When I select a node in the treeView it should display the sum of the times for each children/grandchildrens (every node contains an integer time variable) pretty much like the usual examples with hierarchy tree over a company and when a boss is selected it should总结下属的工资。但不知为何,它只是总结了孩子们的时代,可以说在下属名单上只下降了一级。
希望我想要达到的目标很清楚,如果不是,请告诉我,我会尝试进一步解释!
// This is in the Form1 class and is calles when a node is selected in a treeView:
private void getTimeSum(ProductionElement prod)
{
int sum;
sum = prod.getSumOfTimes();
totalTimeLabel.Text = sum.ToString();
}
class CompositeElement : ProductionElement
{
//The composite class for the composite pattern
protected List<ProductionElement> subordinates = new List<ProductionElement>();
public int getSumOfTimes()
{
int sum;
foreach (var prodel in subordinates)
{
sum += prodel.getIdealTime();
}
return sum;
}
public int getIdealTime()
{
return idealTime;
}
}
【问题讨论】:
-
foreach工作得很好——你根本不了解复合模式。 -
@JohnSaunders 是的,你可能是对的!让我对示例中的模式感到困惑的是,有时用户应该为复合设置时间,有时应该使用叶子计算该复合的时间(以及该复合的父级等等)。更准确地说,活动(组合)基于基于元素(叶子)的子活动(组合)。但是,如果不想通过使用元素构建子活动来获得时间,则可以设置该子活动的时间,并且仍然可以正确地获得该活动的时间。