将树结构转换为不同类型

Ton*_*Nam 4 c# tree casting data-structures

如果我有班级:

class NodeA
{
      public string Name{get;set;}
      public List<NodeA> Children {get;set;}
      // etc some other properties
}
Run Code Online (Sandbox Code Playgroud)

和其他一些课程:

class NodeB
{
      public string Name;
      public IEnumerable<NodeB> Children;
      // etc some other fields;
}
Run Code Online (Sandbox Code Playgroud)

如果我需要将NodeB对象转换为NodeA类型,那么最佳方法是什么?创建一个包装类?如果我必须创建一个包装类,我怎么能创建它,以便所有的wpf控件仍然能够成功绑定到属性?

  • 我需要创建这样的演员的原因:

    在编译程序中返回符号列表(IMemorySymbol)的程序上使用了一种旧算法.我们已经工作并创建了一个新算法,字段和属性有些不同(ISymbolElem).我们需要执行临时转换,以便在wpf应用程序的视图中显示属性.

Tom*_*ear 5

一对夫妇接近......

复制构造函数

有一个NodeA和NodeB包含一个相反的构造函数:

class NodeA 
{ 
    public string Name{get;set;} 
    public List<NodeA> Children {get;set;} 

    // COPY CTOR
    public NodeA(NodeB copy)
    {
        this.Name = copy.Name;
        this.Children = new List<NodeA>(copy.Children.Select(b => new NodeA(b));
        //copy other props
    }
} 
Run Code Online (Sandbox Code Playgroud)

显式或隐式算子

显而易见,你会倾向于NodeA a = (NodeA)b;,而隐含你可以跳过parens.

public static explicit operator NodeA(NodeB b)
{
    //if copy ctor is defined you can call one from the other, else
    NodeA a = new NodeA();
    a.Name = b.Name;
    a.Children = new List<NodeA>();

    foreach (NodeB child in b.Children)
    {
        a.Children.Add((NodeA)child);
    }
}
Run Code Online (Sandbox Code Playgroud)