c# - 通用节点的通用树 C#

标签 c# .net generics

我正在尝试创建通用节点对象的通用树类。

using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Tree<Node<int>> tree = new Tree<Node<int>>();
    }
}

public class Tree<T> : IEnumerable<T>
    where T : IComparable<T>
{
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

public class Node<TNode> : IComparable<TNode>
    where TNode : IComparable<TNode>
{
    TNode Value;
    public int CompareTo(TNode other)
    {
        return Value.CompareTo(other);
    }
}

但是在主方法中我收到编译错误:

The type 'BinaryTree.Node<int>' cannot be used as type parameter 'T' in the generic type or method 'Tree<T>'. There is no implicit reference conversion from 'BinaryTree.Node<int>' to 'System.IComparable<BinaryTree.Node<int>>'.

有人可以帮助我了解问题所在吗?

最佳答案

问题出在你的 Node<> 上类 - 你说过 Node与其中的值类型相当。相反,您应该说它与具有相同值的另一个节点相当:

public class Node<TNode> : IComparable<Node<TNode>>
    where TNode : IComparable<TNode>
{
    TNode Value;
    public int CompareTo(Node<TNode> other)
    {
        return Value.CompareTo(other.Value);
    }
}

此时,发现创建了一个 Tree<Node<int>> .

但实际创建一个 Tree<int> 可能会更好,并制作 Tree<T>使用Node<T>相反。这可能更容易使用。毕竟,每棵树都会有节点。用相对较少的代码很难确定,但我怀疑这实际上就是您想要做的。

关于c# - 通用节点的通用树 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59388140/

相关文章:

java - 如何将类型安全对象强制转换为 JComboBox<String>?

c# - Dapper.NET 多映射 TSecond Deserializer 为空

c# - SQLite 1.0.65 程序集绑定(bind)错误

c# - 无法将 lambda 表达式转换为类型 'ServiceLifetime',因为它不是 Asp.net core 2.2 上的委托(delegate)类型

c# - 如何在 SignalR 客户端中使用带有 hub.On 的异步/等待

generics - Kotlin 中具有泛型的优雅事件处理程序

swift - Swift 中的通用尾部

c# - 窗口 ResizeMode 绑定(bind)到设置

c# - 哪种是为应用程序编写日志的最基于性能的方法

c# - 更改没有 "Password Expired dialog box"的过期密码