通用字典比较

bre*_*ton 3 c# generics

我有一个问题,我似乎无法绕过我的脑袋.我正在创建一个类来保存具有泛型类型的项的字典.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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

所以第一个问题是处理具有不同大小写的字符串; 我通过强制数据为大写来解决这个问题.然而,现在,我发现有一些特定于文化的角色,所以如果没有不变的文化切换,ContainsKey将返回false.

我试过创建一个新的IEqualityComparer,但永远不会被解雇.有任何想法吗?

wdo*_*jos 5

请尝试以下方法:

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

或者(使用三元运算符):

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

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

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

  • 在编辑之前将其变成三元表达式会更好. (2认同)
  • 或者,如果你想要*真正的短代码*你可以使用`this._cache = new Dictionary <TIndex,TItem>(StringComparer.CurrentCultureIgnoreCase as IEqualityComparer <TIndex>)`:D (2认同)