开发者

How to indentify matching type in generic class

I have a generic class of

public class Mapper<K, L, V> : Dictionary<K, V>

When I instantiate it as

Mapper<string, string, MapSource> Map= new Mapper<stri开发者_运维问答ng, string, MapSource>();

and try and do

Map["..."].

is comes back with compiler error message of

The call is ambiguous between the following methods or properties: 'MinorTesting.XML.Sourcer.Mapper.this[L]' and 'MinorTesting.XML.Sourcer.Mapper.this[K]'

How would I fix this to remove the compile .

Bob.


So your class looks like this:

public class MultiKeyDictionary<K, L, V>
{
    public V this[K key]
    {
        get { return... }
    }

    public V this[L key]
    {
        get { return... }
    }
}

So if both K and L are string in your constructed type, you essentially have this:

public class MultiKeyDictionary
{
    public V this[string key]
    {
        get { return... }
    }

    public V this[string key]
    {
        get { return... }
    }
}

Obviously this won't work. The problem is with the specific generics approach here - you could safely support two keys of the same type by replacing the Item properties with something like:

public V GetByK(K key)
{
    ...
}

public V GetByL(L key)
{
    ...
}


What does MultiKeyDictionary look like and where/how is it used?

It looks like MultiKeyDictionary provides two indexers, this[L] and this[K]. When L and K are the same then the compiler is unable to choose between those indexers because they've effectively both become this[string].

One option would be to provide explicit methods to use in place of the indexer in this case: for example, GetByKey(K) and GetByValue(L) or similar.


Your class inherits from Dictionary<K, V>, which implicitly defines the this[K] accessor into your class. When you define the this[L] accessor explicitly, and K and V coincide, you get the conflict.

You should not inherit from Dictionary, in my opinion. You might want to encapsulate a dictionary for internal usage.


May be simply like this.

public class Mapper<K, L, V> : Dictionary<K, V>
{
     public V this[K key1, L Key2]
    {
        get { return  (key1 != null) ? dic[key1] : dic[Key2]; }
    }

}

To access this

Mapper<string, string, int> a = new Mapper<string, string, int>();
var s = a[null, "sam"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜