Type of conditional expression cannot be determined (Func)(无法确定条件表达式的类型 (Func))
问题描述
将方法分配给 Func-type 时,我收到编译错误 无法确定条件表达式的类型,因为方法组"和方法组"之间没有隐式转换'代码>.
When assigning a method to a Func-type, I get the compilation error Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.
这只发生在 上?: 运算符.代码:
This only happens with the ? : operator. The code:
public class Test
{
public static string One(int value)
{
value += 1;
return value.ToString();
}
public static string Two(int value)
{
value += 2;
return value.ToString();
}
public void Testing(bool which)
{
// This works
Func<int, string> actionWorks;
if (which) actionWorks = One; else actionWorks = Two;
// Compilation error on the part "One : Two"
Func<int, string> action = which ? One : Two;
}
}
我发现 一些关于协变和逆变的信息,但我不明白这如何适用于上述情况.为什么这不起作用?
I found some information about co- and contravariance, but I don't see how that applies to the situation above. Why doesn't this work?
推荐答案
您需要显式提供至少一个方法组的签名.但是,在这样做之后,编译器将允许您将 action 声明为隐式类型的本地:
You need to explicitly provide the signature of at least one method group. However, after doing it the compiler will allow you to declare action as an implicitly-typed local:
var action = which ? (Func<int, string>)One : Two;
发生这种情况的原因是 operator ?: 的返回类型不是根据您尝试分配给它的内容推导出来的,而是根据两个表达式的类型推导出来的.如果类型相同或者它们之间存在隐式转换,则编译器推导出返回类型成功;否则,它会抱怨没有转换.
The reason this happens is that the return type of operator ?: is not deduced based on what you are trying to assign it to, but based on the types of the two expressions. If the types are the same or there is an implicit conversion between them, the compiler deduces the return type successfully; otherwise, it complains that there is no conversion.
这篇关于无法确定条件表达式的类型 (Func)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法确定条件表达式的类型 (Func)
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
