简体   繁体   English

为什么编译器在这种情况下无法确定操作数的类型?

[英]Why compiler can't determine the type of operands in this case?

Scratching my head. 抓我的头。 What's wrong with the following statement? 以下陈述有什么问题?

var EncFunc = (encrypt ? Encryption.Encrypt : Encryption.Decrypt);

encrypt is bool , both of the functions Encryption.Encrypt and Encryption.Decrypt have the same type Func<string, string> , but it tells me that: encryptboolEncryption.EncryptEncryption.Decrypt这两个函数具有相同的类型Func<string, string> ,但它告诉我:

CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group' CS0173无法确定条件表达式的类型,因为“方法组”和“方法组”之间没有隐式转换

I have already gone through this and this , but can't understand why compiler cannot determine the type of these 2 functions. 我已经经历过这个这个 ,但无法理解为什么编译器无法确定这两个函数的类型。

NB I know this can be fixed with explicit casting. NB我知道这可以通过显式转换来修复。 I'm more interested in understanding the "why" part. 我对理解“为什么”部分更感兴趣。

I think the following explains why the compiler is having difficulties with this. 我认为以下解释了为什么编译器在这方面遇到了困难。 Let's say we have: 假设我们有:

string MyMethod() { return ""; }

We cannot assign that method to var , in other words we cannot use this: 我们不能将该方法分配给var ,换句话说我们不能使用它:

// Not valid.
var method = MyMethod;

That is because there could be any number of delegates that could be used, for example: 那是因为可以使用任意数量的代表,例如:

delegate string MyDelegate();

With this we now have two options and it seems that it would be wrong for the compiler to assume one over the other: 有了这个,我们现在有两个选项,似乎编译器假设一个在另一个上是错误的:

// Valid.
Func<string> myFunc = MyMethod;

// Valid.
MyDelegate myDel = MyMethod;

EDIT: For the sake of completion I'm adding a reference to this (it was mentioned by OP in the comments). 编辑:为了完成,我添加了对此的引用(OP在评论中提到)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 嵌套泛型:为什么编译器在这种情况下不能推断出类型参数? - Nested Generics: Why can't the compiler infer the type arguments in this case? 泛型:为什么编译器在这种情况下不能推断出类型参数? - Generics: Why can't the compiler infer the type arguments in this case? 为什么不能从约束中确定类型推断 - Why can't type inference determine type from constraints 为什么编译器不能推断出这个select调用的类型? - Why can't the compiler infer the type for this select call? 为什么编译器不能从使用中推断出这种类型的参数 - Why can't the compiler infer this type argument from usage 为什么在这种情况下编译器不会抱怨? - why in this case the compiler doesn't complain? 为什么编译器不能决定类型 - Why can not the Compiler decide the type 运算符“ &amp;&amp;”不能应用于类型为“ int”和“ bool”的操作数(最小差) - Operator '&&' can't be applied to operands of type 'int' and 'bool' (minimum difference) 运算符&#39;&amp;&amp;&#39;不能应用于&#39;int&#39;和&#39;bool&#39;类型的操作数 - Operator '&&' can't be applied to operands of type 'int' and 'bool' 操作数“ +”不能应用于字符串类型和方法组的操作数 - The operand '+' can't be applied to operands of type string and method group
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM