简体   繁体   中英

Unable to constrain generic type

I can't figure out what's happening here. I'm building a wrapper for a Dictionary collection. 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).

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>'."

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. Any thoughts on what's going on?

Original definition of 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> :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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