Unable to constrain generic type

萝らか妹 提交于 2021-02-16 21:17:08

问题


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...
}

回答1:


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.



来源:https://stackoverflow.com/questions/7761975/unable-to-constrain-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!