gpt4 book ai didi

c# - 从 dict.AsQueryable() 获取原始字典

转载 作者:太空狗 更新时间:2023-10-29 20:16:43 26 4
gpt4 key购买 nike

我有一个通用字典,它传递给一个只接受 IQueryable 作为参数的方法

是否可以将可查询对象转换回原始字典?我并不是说用 .ToDictionary(...)

创建一个新字典
private static void Main()
{

var dict = new Dictionary<int, int>();
dict.Add(1,1);

SomeMethod(dict.AsQueryable());

}

public static void SomeMethod(IQueryable dataSource)
{
// dataSource as Dictionary<int, int> --> null
var dict = dataSource.???
}

我知道在这个简单的例子中这没有多大意义。但总的来说,我有一个接口(interface),它要求我返回一个 IQueryable 作为数据源。在实现时返回一个字典。在我的代码的不同位置,我有处理数据源的类。

处理器知道数据源将是一个字典,但如果我已经有一个字典,我不想再创建另一个字典。

最佳答案

.AsQueryable()扩展方法返回 EnumerableQuery<T> wrapper class 的一个实例如果调用它的对象还不是 IQueryable<T> .

这个包装类有一个 .Enumerable属性(property) internal提供对 .AsQueryable() 的原始对象的访问权限被召唤。所以你可以这样做来取回你原来的字典:

var dict = new Dictionary<int, int>();
dict.Add(1,1);
var q = dict.AsQueryable();



Type tInfo = q.GetType();
PropertyInfo pInfo = tInfo.GetProperties(BindingFlags.NonPublic |
BindingFlags.Instance)
.FirstOrDefault(p => p.Name == "Enumerable");
if (pInfo != null)
{
object originalDictionary = pInfo.GetValue(q, null);

Console.WriteLine(dict == originalDictionary); // true
}

但是,这通常是一个非常糟糕的主意。 internal成员的访问受限是有原因的,我认为不能保证 .AsQueryable() 的内部实现将来的某个时候不会改变。因此,最好的办法是要么找到一种方法使原始词典易于访问,要么继续制作新词典。


一种可能的解决方法(不是很好)是制作您自己的包装类来携带字典:

private class DictionaryQueryHolder<TKey, TValue> : IQueryable<KeyValuePair<TKey, TValue>>
{
public IDictionary<TKey, TValue> Dictionary { get; private set; }
private IQueryable<KeyValuePair<TKey, TValue>> Queryable { get; set; }

internal DictionaryQueryHolder(IDictionary<TKey, TValue> dictionary)
{
Dictionary = dictionary;
Queryable = dictionary.AsQueryable();
}

public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return Queryable.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public Expression Expression
{
get { return Queryable.Expression; }
}

public Type ElementType
{
get { return Queryable.ElementType; }
}

public IQueryProvider Provider
{
get { return Queryable.Provider; }
}
}

这都可以作为字典的 IQueryable<T> 的包装器。并提供对原始词典的访问。但另一方面,任何试图检索字典的人都必须知道泛型类型参数是什么(例如 <string, string><int, string> 等)才能成功转换它。

关于c# - 从 dict.AsQueryable() 获取原始字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27902482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com