简体   繁体   English

无法限制通用类型

[英]Unable to constrain generic type

I can't figure out what's happening here. 我不知道这里发生了什么。 I'm building a wrapper for a Dictionary collection. 我正在为Dictionary集合构建包装器。 The idea is that, when the size of the collection is small, it will use a normal in-memory Dictionary; 这个想法是,当集合的大小很小时,它将使用普通的内存字典; but, when a threshold number of items is reached, it will internally switch to an on-disk Dictionary (I'm using the ManagedEsent PersistentDictionary class). 但是,当达到项目的阈值数量时,它将在内部切换到磁盘上的Dictionary(我使用的是ManagedEsent PersistentDictionary类)。

A snippet of the on-disk version is below. 下面是磁盘版本的片段。 When compiling, it fails with the following error: 编译时,它失败并显示以下错误:

"The type 'T_KEY' cannot be used as type parameter 'TKey' in the generic type or method 'Microsoft.Isam.Esent.Collections.Generic.PersistentDictionary<TKey,TValue>'. There is no boxing conversion or type parameter conversion from 'T_KEY' to 'System.IComparable<T_KEY>'." “类型'T_KEY'不能用作通用类型或方法'Microsoft.Isam.Esent.Collections.Generic.PersistentDictionary <TKey,TValue>'中的类型参数'TKey'。没有装箱转换或类型参数转换从“ T_KEY”到“ System.IComparable <T_KEY>”。

So I modified the class definition to be: 因此,我将类定义修改为:

class DiskDictionary<T_KEY, T_VALUE> : IHybridDictionary<T_KEY, T_VALUE>
    where T_KEY : System.IComparable

thinking that would do the trick, but it didn't. 认为可以解决问题,但没有成功。 I tried constraining the definition IHybridDictionary too but that didn't have any effect. 我也尝试限制IHybridDictionary的定义,但这没有任何效果。 Any thoughts on what's going on? 有什么想法吗?

Original definition of DiskDictionary: DiskDictionary的原始定义:

class DiskDictionary<T_KEY, T_VALUE> : IHybridDictionary<T_KEY, T_VALUE>
{
    string dir;
    PersistentDictionary<T_KEY, T_VALUE> d;

    public DiskDictionary(string dir)
    {
        this.dir = dir;
        //d = new PersistentDictionary<T_KEY, T_VALUE>(dir);
    }

    ... some other methods...
}

Your DiskDictionary class need to specify that T_KEY implements IComparable<TKey> : 您的DiskDictionary类需要指定T_KEY实现IComparable<TKey>

class DiskDictionary<T_KEY, T_VALUE> : IHybridDictionary<T_KEY, T_VALUE>
    where T_KEY : System.IComparable<T_KEY>
{
}

There is both a generic and a non generic version of this interface and you were specifying the wrong one. 该接口既有通用版本又有非通用版本,您指定的是错误的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM