繁体   English   中英

将树结构转换为不同类型

[英]Cast/Convert tree structure to different type

如果我有班级:

class NodeA
{
      public string Name{get;set;}
      public List<NodeA> Children {get;set;}
      // etc some other properties
}

和其他一些课程:

class NodeB
{
      public string Name;
      public IEnumerable<NodeB> Children;
      // etc some other fields;
}

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

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

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

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

复制构造函数

有一个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
    }
} 

显式或隐式算子

显然你会像NodeA a = (NodeA)b;一样投射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);
    }
}

如果您不关心将NodeA的实现耦合到NodeB ,那么添加一个复制构造函数,如下所示:

class NodeA
{
    public NodeA() { }
    public NodeA(NodeB node)
    {
        Name = node.Name;
        Children = node.Children.Select(n => new NodeA(n)).ToList();
    }

    public string Name{get;set;}
    public List<NodeA> Children {get;set;}
    // etc some other properties
}

如果需要关联,那么您可以创建一个Convert -style类来为您进行转换。 请注意, Automapper框架通过使用源和目标类型的反射为您生成这些类型的转换。

如何从通用接口继承?

interface INode {
  public string Name{get;set;}
  public IEnumerable<INode> Children {get;set;}
}

class NodeA : INode {
  public string Name{get;set;}
  public List<NodeA> Children {get;set;}
  // etc some other properties
}

class NodeB : INode {
  public string Name;
  public IEnumerable<NodeB> Children;
  // etc some other fields;
}

void myMethod() {
  INode nodeB = new NodeB();
  INode nodeA = nodeB;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM