[英]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.