我有两个类,它们来自两个项目:生产和测试。
BinaryTreeNode
-来自一个基础项目,我无法更改。
TreeNode
-来自一个测试项目,我可以更改。
我想在测试项目中可互换地使用这些类,并在没有任何问题的情况下从一个类转换到另一个类(或者至少从BinaryTreeNode转换到TreeNode(。我可以用C#做这个吗?如果是,如何?因为如果我派生它就不起作用(创建为BinaryTreeNode/base的对象不能转换为TreeNode/derived(。我不能使用铸造运算符,因为道具的类型相同,它不起作用。知道吗?
public class BinaryTreeNode {
public BinaryTreeNode(int key) {
this.Key = key;
this.Color = 0;
}
public int Key { get; set; }
public BinaryTreeNode Left { get; set; }
public BinaryTreeNode Right { get; set; }
public BinaryTreeNode Parent { get; set; }
/// <summary>
/// 0 = Red
/// 1 = Black
/// </summary>
public Color Color { get; set; }
/// <summary>
/// AVL Balance item
/// </summary>
public int Balance { get; set; }
}
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
您可以编写一个递归ToTreeNode
函数,将所有值复制到TreeNode
的新实例中。
public static class Extensions
{
public static TreeNode ToTreeNode(this BinaryTreeNode binary)
{
var treeNode = new TreeNode(binary.Key);
treeNode.left = binary.Left?.ToTreeNode();
treeNode.right = binary.right?.ToTreeNode();
}
}
如果只使用C# 4.0
很重要,那么就必须这样写:
public static class Extensions
{
public static TreeNode ToTreeNode(this BinaryTreeNode binary)
{
var treeNode = new TreeNode(binary.Key);
if (binary.Left != null)
treeNode.left = binary.Left.ToTreeNode();
if (binary.Right != null)
treeNode.right = binary.right.ToTreeNode();
}
}
更新1
如果你真的想使用强制转换,你可以实现C#的explicit operator
功能。(我不知道措辞是否正确。(
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
public static explicit operator TreeNode(BinaryTreeNode b)
{
return b.ToTreeNode();
}
}
但采用这种方法有几个缺点:
-使用node.ToTreeNode()
比使用(TreeNode)node
要干净得多
-浏览代码比较困难
-您必须编辑现有的TreeNode
类。所以你打破了Open-Close Principle
。