我可以在C#中创建两个可互换的类吗?或者类似的推荐方法是什么? 更新1

我有2个班级,来自2个项目:生产和测试。

BinaryTreeNode-来自基础项目,我无法更改。

TreeNode-来自一个测试项目,我可以更改。

我想在测试项目中互换使用这些类,并毫无问题地从一个转换为另一个(或至少从BinaryTreeNode转换为TreeNode)。我可以在C#中执行此操作吗?如果是,怎么办?因为如果我推导它不起作用(创建为BinaryTreeNode / base的对象不能强制转换为TreeNode /派生)。由于无法使用相同类型的道具,因此无法使用强制转换运算符。有想法吗?

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; }
}
ayihaimin 回答:我可以在C#中创建两个可互换的类吗?或者类似的推荐方法是什么? 更新1

您可以编写一个递归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功能。 (我不知道措词是否正确。:D)

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

本文链接:https://www.f2er.com/3075848.html

大家都在问