[英]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: encrypt
是bool
, Encryption.Encrypt
和Encryption.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.