You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Main方法实例化Tree并用Iterative Deepening Search遍历,解决泛型约束报错

报错原因

Tree<K,V>对泛型参数K设置了class, IComparable<K>约束,你自定义的IterativeDeepeningSearch.Key类未实现IComparable<IterativeDeepeningSearch.Key>接口,因此不符合泛型约束要求,触发编译报错。

解决方案

方案1:修改自定义Key类满足约束

给Key类实现IComparable<Key>接口,示例实现如下:

namespace IterativeDeepeningSearch
{
    public class Key : IComparable<Key>
    {
        // 示例属性,可根据实际业务替换为你需要的字段
        public int KeyId { get; set; }

        // 实现IComparable<Key>接口要求的CompareTo方法
        public int CompareTo(Key other)
        {
            if (other == null) return 1;
            // 自定义比较规则,这里按KeyId比较
            return this.KeyId.CompareTo(other.KeyId);
        }

        // 可选优化:适配原Tree代码中的==比较逻辑,改为按值比较
        public override bool Equals(object obj)
        {
            return obj is Key key && KeyId == key.KeyId;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(KeyId);
        }

        public static bool operator ==(Key left, Key right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(Key left, Key right)
        {
            return !Equals(left, right);
        }
    }
}

修改完成后即可正常实例化Tree类:

// V可替换为你需要的任意引用类型
var tree = new Tree<Key, string>();

方案2:删除Tree类多余的泛型约束

原Tree代码的搜索逻辑仅使用==判断键相等,没有调用任何IComparable<K>接口的方法,该约束属于冗余约束,可直接删除:

// 移除K的IComparable<K>约束
public class Tree<K, V>
     where K : class
     where V : class
{
    private Node<K, V> root;

    public V DepthLimitedSearch(Node<K, V> root, K goal, int depth)
    {
        if (depth == 0 && root.key == goal)
        {
            return root.value;
        }
        else if (depth > 0)
        {
            foreach (var child in root.children)
            {
                var result = DepthLimitedSearch(child, goal, depth - 1);
                if (result != default(V))
                {
                    return result;
                }
            }
            return default(V);
        }
        else
        {
            return default(V);
        }
    }

    public V IterativeDeepeningSearch(K key, int depth)
    {
        for (int currentDepth = 0; currentDepth <= depth; currentDepth++)
        {
            var v = DepthLimitedSearch(root, key, currentDepth);
            if (v != default(V))
            {
                return v;
            }
        }
        return default(V);
    }

    // 内部Node类的约束也对应移除
    public class Node<K, V>
        where K : class
        where V : class
    {
        public K key;
        public V value;
        public Node<K, V>[] children;
    }
}

修改后只要自定义Key是引用类型,即可直接作为泛型参数传入Tree类。

注意事项

原Tree代码中默认的==比较为引用比较,如果需要按键的业务值匹配,要么按方案1重写==运算符,要么将搜索逻辑中的root.key == goal修改为root.key.Equals(goal)。

内容的提问来源于stack exchange,提问作者SwordLion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:39:04