【发布时间】:2021-02-25 08:16:32
【问题描述】:
我有以下代码:
private T? FromCache<T>(CacheKey key, Func<T?> retriever)
{
if (cache.TryGetValue(key, out T res))
return res;
res = retriever();
if (res is not null)
cache.Set(key, res);
return res;
}
public decimal? GetClosingExchangeRate(string sourceCurrencyCode, string targetCurrencyCode)
{
return FromCache<decimal>(CacheKey.Closing(sourceCurrencyCode, targetCurrencyCode),
// The following line results in this error:
// Error CS0266 Cannot implicitly convert type 'decimal?' to 'decimal'.An explicit conversion exists (are you missing a cast?)
() => GetExchangeRate(sourceCurrencyCode, targetCurrencyCode)?.ClosingRate
);
}
public ExchangeRateDefinition? GetExchangeRate(string sourceCurrencyCode, string targetCurrencyCode)
{
return GetExchangeRateQuery(sourceCurrencyCode, targetCurrencyCode).FirstOrDefault();
}
public class ExchangeRateDefinition
{
[...]
public decimal? ClosingRate { get; set; }
[...]
}
在这种情况下,
我不明白这个错误:据我了解,传递给 FromCache 方法的委托的返回类型为T?,它应该转换为decimal?,这正是我使用的委托返回的时间。然而,错误消息似乎表明编译器正在期待一个返回非可空小数的委托。
为什么会出现此错误,我该如何解决?
【问题讨论】:
-
return FromCache<decima?>也许.. 无论如何这远不是一个可重现的例子,我粘贴你的代码,其中大部分是错误 -
您的问题似乎与 C# 版本 9 无关。我已经删除了那个标签,因为它不合适。如果您觉得您的问题是特定于 C# 9,您需要编辑帖子以说明原因。 FWIW,我同意之前的评论,即这个问题是不充分的,因为它缺乏适当的minimal reproducible example。另请参阅How to Ask,了解有关如何以清晰、可回答的方式提出问题的更多信息。