在字典中查询唯一的通用对象

query a dictionary for unique generic objects

我正在尝试编写一个 returns 通用对象的通用方法。该方法将采用通用类型并使用它来查询集合,以查找具有匹配类型的对象。

我已尝试将此对象添加到集合中,但出现编译错误。 cannot convert from CustomSet<AppLog>' to 'CustomSet<System.Type>'

如何才能满足这个规格?

public CustomSet<TEntity> Set<TEntity>() where TEntity : class
{
    Type key = typeof(TEntity);

    if (allSets.ContainsKey (key))
    {
        return allSets[key];
    }
}

private static readonly Dictionary<Type, CustomSet<Type>> allSets = new Dictionary<Type, CustomSet<Type>>()
{
    {typeof(AppLog), AppLogs}
};

public static CustomSet<AppLog> AppLogs { get; set; }

编辑

代码已更新,因此只会出现提到的编译错误

您需要 appSets 词典的类型安全性较低才能实现这一点。将其定义为 Dictionary<Type, object> 并在检索后将项目转换回 CustomSet<TEntity>

private static readonly Dictionary<Type, object> allSets = new Dictionary<Type, object>.Add(typeof(AppLog), AppLogs);

public CustomSet<TEntity> Set<TEntity>() where TEntity : class
{
    Type key = typeof (TEntity);       

    if (allSets.ContainsKey(key))
    {
        return (CustomSet<TEntity>)allSets[key];
    }
}