Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

milen.stefanov avatar milen.stefanov 40 Точки

Ето ти Element класа: Display(int depth) метода се вика рекурсивно, ако в съответния елемент има вложени други елементи (children.Count > 0).

namespace Composite.Element
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class Element
    {
        private IList<Element> children;

        public Element(string type, params Element[] children)
        {
            this.Type = type;
            this.children = new List<Element>(children);
        }

        public string Type { get; private set; }

        public void Add(Element child)
        {
            if (child == null)
            {
                throw new ArgumentNullException();
            }

            this.children.Add(child);
        }

        public void Remove(Element child)
        {
            if (this.children.Contains(child))
            {
                this.children.Remove(child);
            }

            throw new ArgumentException();
        }

        public string Display(int depth)
        {
            string intend = new string(' ', depth);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("{1}<{0}>", this.Type, intend));

            if (this.children.Count != 0)
            {
                foreach (var element in this.children)
                {
                    sb.Append(element.Display(depth + 2));
                }
            }

            sb.AppendLine(string.Format("{1}</{0}>", this.Type, intend));

            return sb.ToString();
        }
    }
}

0
milen.stefanov avatar milen.stefanov 40 Точки

Само че си виждам грешка в Remove метода. По-вярното е:

if (!this.children.Contains(child))
{
    throw new ArgumentException();

}            

this.children.Remove(child);

0
milen.stefanov avatar milen.stefanov 40 Точки

Ето ти Main-a: добавил съм ред Console.WriteLine(html.Display(0)), за да ти се визуализира output-a на конзолата.

namespace DOMBuilder
{
    using System;
    using System.IO;
    using Composite.Element;

    public class Program
    {
        public static void Main()
        {
            Element html = new Element("html",
                                            new Element("head"),
                                            new Element("body",
                                                new Element("section",
                                                    new Element("h2"),
                                                    new Element("p"),
                                                    new Element("span")),
                                                new Element("footer")));

            Console.WriteLine(html.Display(0));
            File.WriteAllText("index.html", html.Display(0));
        }
    }
}

0
20/08/2015 14:10:17
Stanislav.Georgieff avatar Stanislav.Georgieff 4 Точки

Thanks колега, ето го и моето решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace DOMBuilder
{
    public class Element
    {

        private string type;
        private ICollection<Element> children;

        public Element(string type, params Element[] children)
        {
            this.Type = type;
            this.children = new List<Element>();
            for (int i = 0; i < children.Length; i++)
            {
                this.children.Add(children[i]);
            }

        }

        public string Type
        {
            get { return this.type; }
            set { this.type = value; }
        }

        public void Add(Element element)
        {
            this.children.Add(element);
        }

        public void Remove(Element element)
        {
            if (this.children.Contains(element))
            {
                this.children.Remove(element);
            }
            else
            {
                throw new ArgumentNullException("The element doesn't exist in the children collection.");
            }
        }

        public string Display(int deapth = 0)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("{0}<{1}>", new string(' ', deapth), this.Type.ToString()));
            if (this.children.Count > 0)
            {
                foreach (var element in this.children)
                {
                    sb.AppendLine(element.Display(deapth + 1));
                }
            }
            sb.Append(string.Format("{0}</{1}>", new string(' ', deapth), this.Type.ToString()));

            return sb.ToString();
        }

    }
}

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.