gpt4 book ai didi

c# - 无法从用法中推断出方法的类型参数。尝试具体指定类型参数

转载 作者:行者123 更新时间:2023-11-30 23:07:18 25 4
gpt4 key购买 nike

我正在尝试使用表达式和泛型来创建一组泛型方法来帮助构建字典,其中字典的键和值的类型可以是任何类型。

到目前为止我有:

public class DictionaryServices<T>
{
private readonly IGenericRepository<T> _repo;

public DictionaryServices(IGenericRepository<T> repo)
{
_repo = repo;
}

public Dictionary<TKey, TValue> BuildDictionary<TObject, TKey, TValue>(Expression<Func<TObject, TKey>> keyExp, Expression<Func<TObject, TValue>> valueExp)
{
var allItems = _repo.GetAll();
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
foreach (var item in allItems)
{
var keyMe = keyExp.Body as MemberExpression;

dictionary.Add(GetValue(keyExp, item), GetValue(valueExp, item));
}
return dictionary;
}

private TType GetValue<TObject, TType>(Expression<Func<TObject, TType>> exp, TObject item)
{
var me = exp.Body as MemberExpression;
var propInfo = me.Member as PropertyInfo;
return (TType)propInfo.GetValue(item, null);
}
}

编译时出现错误“无法从用法中推断出方法的类型参数。请尝试具体指定类型参数。”对于 GetValue 的两种用法,但我不明白为什么。如果我删除 GetValue 函数并复制它对 foreach 中的键和值所做的操作,那么它就可以正常工作。有谁知道为什么我会收到此错误?

最佳答案

您的BuildDictionary 定义中不需要TObject 泛型参数,因为您的类< 中已经有T 参数/em> 具有相同含义的定义(即 - T 是您存储库中的对象类型)。所以像这样更改 BuildDictionary:

public Dictionary<TKey, TValue> BuildDictionary<TKey, TValue>(
Expression<Func<T, TKey>> keyExp,
Expression<Func<T, TValue>> valueExp)

您还可以从 GetValue 中删除 TObject,但这不是必需的:

private TType GetValue<TType>(Expression<Func<T, TType>> exp, T item)

您当前的方法不起作用,因为您有两个具有相同含义的不同泛型类型参数:类级别的 T 和方法级别的 TObject。您的 _repo.GetAll() 返回 T 的列表,但方法适用于 TObject 类型的对象,这可能不同。

关于c# - 无法从用法中推断出方法的类型参数。尝试具体指定类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451234/

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