2014-10-29 5 views
0

Я использую библиотеку третьей стороны, где, если я хотел созданную вложенную структуру каталогов, которые я должен создать как этотСоздание вложенных объектов динамически

new ClassA("folder1", new ClassA("folder2", new ClassA("folder3"))); 

это создаст структуру папок, как это folder1-> folder2-> folder3 ,

Чтобы сделать это простым для моих пользователей, я создаю методы, в которых пользователи передают путь как параметр, а мой метод обрабатывает путь и должен создавать указанную выше структуру объектов, которая внутренне создает структуру папок.

прямо сейчас я могу разобрать путь как дерево, но не смог создать выше структуру объекта. Это пример кода консольного приложения

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<string> Paths = new List<string>(); 
     Paths.Add("D1"); 
     Paths.Add("E1"); 
     Paths.Add(@"E1\E11"); 
     Paths.Add(@"D1\D11"); 
     Paths.Add(@"D1\D12"); 
     Paths.Add(@"D1\D2"); 
     Paths.Add(@"D1\D2\D21"); 

     Node nodeObj = new Node(); 

     foreach (var path in Paths) 
     { 
      nodeObj.AddPath(path); 
     } 

     //var nodes = nodeObj.Nodes; 
     Node current = nodeObj; 
     int level = 0; 
     ReadNodes(current, level); 

    } 

    private static void ReadNodes(Node current, int level) 
    { 
     foreach (string key in current.Nodes.Keys) 
     { 
      var tablevel = level; 
      string tab = string.Empty; 
      while (tablevel>0) 
      { 
       tab = tab + " "; 
       tablevel--; 
      } 
      Console.WriteLine(tab +":" + key); 

      // The child node. 
      Node child; 

      if (current.Nodes.TryGetValue(key, out child) && child.Nodes.Count>0) 
      { 
       ReadNodes(child, level+1); 
      } 
      else { } 

     } 
    } 
} 

public class Node 
{ 
    private readonly IDictionary<string, Node> _nodes = 
     new Dictionary<string, Node>(); 

    public IDictionary<string, Node> Nodes 
    { 
     get { return _nodes; } 
    } 

    private string Path { get; set; } 

    public string Source { get; set; } 

    public void AddPath(string path) 
    { 
     char[] charSeparators = new char[] { '\\' }; 

     // Parse into a sequence of parts. 
     string[] parts = path.Split(charSeparators, 
      StringSplitOptions.RemoveEmptyEntries); 

     // The current node. Start with this. 
     Node current = this; 

     // Iterate through the parts. 
     foreach (string part in parts) 
     { 
      // The child node. 
      Node child; 

      // Does the part exist in the current node? If 
      // not, then add. 
      if (!current._nodes.TryGetValue(part, out child)) 
      { 
       // Add the child. 
       child = new Node 
       { 
        Path = part 
       }; 

       // Add to the dictionary. 
       current._nodes[part] = child; 
      } 

      // Set the current to the child. 
      current = child; 

     } 
    } 
} 

ответ

0
class Test : yourClass 
{ 
    string name; 
    Test childTest; 

    public Test(string name) 
    { 
     this.name = name; 
     this.childTest = null; 
    } 
    public Test(string name, Test test) 
    { 
     this.name = name; 
     this.childTest = test; 
    } 
} 

Test a = new Test("a", new Test("b", new Test("c"))); 

Вы просто ищете структуры, как это? Вам нужны два конструктора, которые принимают только строку и одну, которая принимает строку и другой класс того же типа.

+0

Я пытаюсь создать слой над третьей библиотекой, чтобы упростить работу для моих пользователей. – PSR

+0

попробуйте сделать это так, чтобы вы наследовали верхний класс, вы, вероятно, собираетесь делать базовые вызовы в зависимости от того, как работает ваш класс – Vajura