C# 查询字典以查找唯一的泛型对象

C# 查询字典以查找唯一的泛型对象,c#,generics,generic-collections,C#,Generics,Generic Collections,我正在尝试编写一个返回泛型对象的泛型方法。该方法将采用泛型类型,并使用它为具有匹配类型的对象查询集合 我已尝试过,但在尝试将此对象添加到集合时出现编译错误无法从“自定义集”转换为“自定义集” 我怎样才能达到这个规格 public CustomSet<TEntity> Set<TEntity>() where TEntity : class { Type key = typeof(TEntity); if (allSets.ContainsKey (key

我正在尝试编写一个返回泛型对象的泛型方法。该方法将采用泛型类型,并使用它为具有匹配类型的对象查询集合

我已尝试过,但在尝试将此对象添加到集合时出现编译错误<代码>无法从“自定义集”转换为“自定义集”

我怎样才能达到这个规格

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; }
public CustomSet(),其中tenty:class
{
Type key=typeof(tenty);
if(allset.ContainsKey(键))
{
返回所有集合[键];
}
}
私有静态只读字典allset=newdictionary()
{
{typeof(AppLog),AppLogs}
};
公共静态自定义集AppLogs{get;set;}
编辑


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

您需要将
应用程序集
字典的类型安全性降低才能实现这一点。将其定义为
Dictionary
,并在检索以下内容后将该项强制转换回
CustomSet

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];
    }
}
private static readonly Dictionary allset=new Dictionary.Add(typeof(AppLog),AppLogs);
public CustomSet()其中tenty:class
{
Type key=typeof(tenty);
if(所有集合容器(键))
{
返回(CustomSet)所有集合[键];
}
}

要实现这一点,您需要
应用程序集
字典的类型安全性更低。将其定义为
Dictionary
,并在检索以下内容后将该项强制转换回
CustomSet

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];
    }
}
private static readonly Dictionary allset=new Dictionary.Add(typeof(AppLog),AppLogs);
public CustomSet()其中tenty:class
{
Type key=typeof(tenty);
if(所有集合容器(键))
{
返回(CustomSet)所有集合[键];
}
}

这可能会起作用:
专用静态只读字典allset=new Dictionary().Add(typeof(AppLog),AppLogs)@FarzanMirheydari-代码没有编译。我更新了代码片段。只会出现编译错误。这可能会起作用:
private static readonly Dictionary allset=new Dictionary().Add(typeof(AppLog),AppLogs)@FarzanMirheydari-代码没有编译。我更新了代码片段。只会出现编译错误。这看起来不错,只是做了一些轻微的修改。我刚刚意识到使用
tenty
作为参数是无效的。只能传递
tenty
类型变量。我将对这个问题进行编辑,如果你对你的答案稍作修改,我将接受。稍作修改后看起来不错。我刚刚意识到使用
tenty
作为参数是无效的。只能传递
tenty
类型变量。我将对这个问题进行编辑,如果你对你的答案稍作修改,我将接受。