我的列表结构如下:
public class Custo{
public int id { get; set; }
public int idParent { get; set; }
public decimal amount{ get; set; }
public decimal unitaryValue{ get; set; }
}
List<Custo> myLIst = new List<Custo>();
我希望我的列表像这样返回:
Name Total Amount Total Value
Projetos 17,00 $70
Arquitetura 15,00 $60
Estrutura 10,00 $35
Modulo 5,00 $25
Desenho 2,00 $10
Artistico 2,00 $10
Projetos Eletricos 0,00 $0
答案 0 :(得分:0)
基本上在复合模式中,您需要三个类。一个是treenode,另外两个将继承。一个是能够养育孩子的项目。另一个是子/节点,将是个人的Custos。
当您使用这些类时,您将创建一个新的Projectos并添加子节点,然后在您希望它们显示时调用Display方法。您显然可以为其他功能添加逻辑。这与此处的代码类似:http://www.dofactory.com/net/composite-design-pattern
用法可能是 主要强>
Projectos project = new Projectos("Projetos");
project.Add(new Custos("Arquitetura", 15, 70.00);
Projectos electricos = new Projectos("Electricos");
electricos.Add(new Custos("custo1", 20, 80.00);
project.Add(electricos);
project.Display();
<强> Projectos 强>
using System;
using System.Collections.Generic;
namespace CompositePatternExercise
{
class Projectos : CustosNode
{
private List<CustosNode> elements = new List<CustosNode>();
// Constructor
public Projectos(string name) : base(name)
{
}
public override void Add(CustosNode d)
{
elements.Add(d);
}
public override void Remove(CustosNode d)
{
elements.Remove(d);
}
public override void Display()
{
decimal totalValue = 0;
decimal totalAmount = 0;
Console.WriteLine(_name);
// Display each child element on this node
foreach (CustosNode d in elements)
{
d.Display();
totalAmount += d.Amount;
totalValue += d.Value;
}
Console.Write("Project total:" + totalAmount.ToString("C") + " " + totalAmount.ToString("C"));
}
}
}
<强>保管人强>
namespace CompositePatternExercise
{
class Custos : CustosNode
{
// Constructor
public Custos(string name, decimal amount, decimal value) : base(name, amount, value)
{
}
public override void Add(CustosNode c)
{
Console.WriteLine(
"Cannot add to a custo");
}
public override void Remove(CustosNode c)
{
Console.WriteLine(
"Cannot remove from a custo");
}
public override void Display()
{
Console.WriteLine(_name + " " + Amount.ToString("C") + " " + Value.ToString("C"));
}
}
}
}
<强> CustosNode 强>
namespace CompositePatternExercise
{
abstract class CustosNode
{
protected string _name;
protected decimal _amount = 0m;
protected decimal _value = 0m;
public decimal Value { get => _value; }
public decimal Amount { get => _amount; }
// Constructor
public CustosNode(string name)
{
this._name = name;
}
public CustosNode(string name, decimal amount, decimal value)
{
this._name = name;
this._amount = amount;
this._value = value;
}
public abstract void Add(CustosNode c);
public abstract void Remove(CustosNode c);
public abstract void Display();
}
}