通用词典比较

本文关键字:比较 通用词 | 更新日期: 2023-09-27 18:21:52

我有一个问题,似乎无法解决。我正在创建一个类来保存具有泛型类型的项的字典。如果索引类型是字符串,则需要强制此字典为InvariantCultureIgnoreCase

例如:

public class Cache<TIndex, TItem>
{
    protected IDictionary<TIndex, TItem> _cache { get; set; }
    public Cache()
    {
        this._cache = new Dictionary<TIndex, TItem>();
    }
    public bool Exists(TIndex index)
    {
        if (!_cache.ContainsKey(index))
        {
            //....do other stuff here
            this._cache.Add(databaseResult.Key, databaseResult.Value);
            return false;
        }
        return true;
    }
} 

因此,第一个问题是处理具有不同资本的字符串;我通过强制数据为大写来解决这个问题。然而,现在我发现有些字符是特定于区域性的,所以如果没有不变的区域性切换,ContainsKey将返回false。

我试过创建一个新的IEqualityComparer,但它永远不会被解雇。有什么想法吗?

通用词典比较

请尝试以下操作:

public Cache()
{
    if (typeof(TIndex) == typeof(string))
    {
        this._cache = new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase);
    }
    else
    {
        this._cache = new Dictionary<TIndex, TItem>();
    }
}

或(带三元运算符):

public Cache()
{
    this._cache = typeof(TIndex) == typeof(string)
                ? new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase)
                : new Dictionary<TIndex, TItem>();
}

或者(真的很短,正如@Rawling所建议的):

public Cache()
{
    this._cache = new Dictionary<TIndex, TItem>(StringComparer.InvariantCultureIgnoreCase as IEqualityComparer<TIndex>);
}

这是我认为您所要求的功能完整的版本(我必须添加Set函数,否则它将基于您自己的代码)。正如if/Console.WriteLine检查所显示的那样,它忽略了大小写。如果这不是你想要的,请进一步澄清你的问题。

class Program
{
    static void Main(string[] args)
    {
        Cache<string, string> stringCache = new Cache<string, string>();
        stringCache.Set("A String Index", "A String Item");
        if (stringCache.Exists("A String Index"))
            Console.WriteLine("Title Case exists");
        if (stringCache.Exists("A STRING INDEX"))
            Console.WriteLine("All Caps Exists");
        if (stringCache.Exists("a string index"))
            Console.WriteLine("All Lowercase Exists");
    }
}
class Cache<TIndex, TItem>
{
    private IDictionary<TIndex, TItem> _cache { get; set; }
    public Cache()
    {
        if (typeof(TIndex) == typeof(string))
        {
            _cache = new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase);
        }
        else
        {
            _cache = new Dictionary<TIndex, TItem>();
        }
    }
    public void Set(TIndex index, TItem item)
    {
        _cache[index] = item;
    }
    public bool Exists(TIndex index)
    {
        if (!_cache.ContainsKey(index))
        {
            return false;
        }
        return true;
    }
}