【问题标题】:Error CS0311 Generic Error in Visual Studio [closed]Visual Studio中的错误CS0311一般错误[关闭]
【发布时间】:2020-11-03 22:44:35
【问题描述】:

错误 CS0311 类型“HashTables.KeyValue”不能用作泛型类型或方法“BinarySearchTree”中的类型参数“Y”。没有从 'HashTables.KeyValue' 到 'System.IComparable>' 的隐式引用转换。

自定义键值类

    public class KeyValue<K,V> where K : IComparable<K> where V : IComparable<V>
        
    {
       
        K key;
        V value;

      
        public KeyValue(K key, V value)
        {
            key = key;
            value = value;
        }

        public K Key
        {
            get
            {
                return key;
            }
        }

        public V Value
        {
            get
            {
                return value;
            }
        }

    }

【问题讨论】:

  • 什么是KeyValue?鉴于它显然没有实现IComparable&lt;KeyValue&lt;K, V&gt;&gt;,为什么您认为应该能够将其用作BST&lt;T&gt; 的类型参数?
  • 在 Stack Overflow 上询问有关错误的问题时,您需要以文本形式提供完整的错误消息内容。请阅读How to Ask 了解有关预期的更多信息。
  • 错误是说KeyValue&lt;V,T&gt; 没有实现IComparable。您只对KeyValue 的泛型类型施加限制,而不是对整个类型施加限制。这会触发错误

标签: c# visual-studio compiler-errors


【解决方案1】:

您只需要稍微更改一下您的 KeyValue。问题是您的 KeyValue 实际上是您要在树中比较的元素(很可能是按值)。为清楚起见,省略了空值检查。

 public class KeyValue<K, V> : IComparable<KeyValue<K, V>>
            where K : IComparable<K>
            where V : IComparable<V>
    {
        //Store the key and the value
        K kKey;
        V vValue;

        public int CompareTo([AllowNull] KeyValue<K, V> other)
        {
            return this.Value.CompareTo(other.Value);
        }

        //Constructor
        public KeyValue(K key, V value)
        {
            kKey = key;
            vValue = value;
        }

        public K Key
        {
            get
            {
                return kKey;
            }
        }

        public V Value
        {
            get
            {
                return vValue;
            }
        } 
    }

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2016-07-25
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多