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)


基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01