根据类型返回通用字典 [英] returning generic Dictionary depending on type

查看:154
本文介绍了根据类型返回通用字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回Dictionary的泛型函数。如果Dictionary的键是一个字符串,我想使用String.OrdinalIgnoreCase比较器。



这是我的代码:

  public static Dictionary< K,V> getDict< K,V>()
{
Dictionary< K,V> aDict;

if(typeof(K)== typeof(string))
{
var stringDict = new Dictionary< string,V>(StringComparer.OrdinalIgnoreCase);
aDict =(Dictionary< K,V>)stringDict; //错误在这里 - 无法转换。
}
else aDict = new Dictionary< K,V>();
//在这里做更多的事
return aDict;
}

但它告诉我它


不能将 Dictionary< string,V> 转换为字典< K,V> / code>。


我应该怎么做?



  var stringDict = new Dictionary< / p> 

K,V>(
StringComparer.OrdinalIgnoreCase as IEqualityComparer< K>);

问题在于 Dictionary< TKey,TValue> ctor期望 IEqualityComparer< T> StringComparer 为您提供 IEqualityComparer - 非泛型变体。一旦你正确地转换了你的等号比较器,你应该在你的路上。



下面的测试代码块将触发预期的异常:

  var dict = getDict< string,int>(); 

dict.Add(alpha,1);
dict.Add(Alpha,2); //触发预期的重复键例外。

HTH ...


I have a generic function that returns a Dictionary. If the key of the Dictionary is a string, I want to use the String.OrdinalIgnoreCase comparer.

This is my code:

    public static Dictionary<K,V> getDict<K,V>()
    {
        Dictionary<K,V> aDict;

        if(typeof(K)==typeof(string)) 
        {
            var stringDict = new Dictionary<string, V>(StringComparer.OrdinalIgnoreCase);
            aDict = (Dictionary<K,V>)stringDict;    // error here - can't convert.
        }
        else aDict = new Dictionary<K, V>();
// do more stuff here
        return aDict;
    }

However it tells me it

can't convert a Dictionary<string,V> to a Dictionary<K,V>.

How should I be doing this?

解决方案

This should work the best for you:

var stringDict = new Dictionary<K, V>(
    StringComparer.OrdinalIgnoreCase as IEqualityComparer<K>);

The problem is that the Dictionary<TKey,TValue> ctor expects an IEqualityComparer<T>. StringComparer gives you an IEqualityComparer - the non-generic variety. Once you cast your equality comparer correctly, you should be on your way.

Test code block below will trigger the expected exception:

var dict = getDict<string, int>();

dict.Add("alpha", 1);
dict.Add("Alpha", 2);  // triggers the expected duplicate key exception.

HTH...

这篇关于根据类型返回通用字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆