使用 ? 分配委托时出错? : 语法
我创建了一个委托和两个匹配方法。
private delegate bool CharComparer(char a, char b);
// Case-sensitive char comparer
private static bool CharCompare(char a, char b)
{
return (a == b);
}
// Case-insensitive char comparer
private static bool CharCompareIgnoreCase(char a, char b)
{
return (Char.ToLower(a) == Char.ToLower(b));
}
当我尝试使用以下语法将这些方法中的任何一个分配给委托时(请注意,此代码位于同一类的静态方法中):
CharComparer isEqual = (ignoreCase) ? CharCompareIgnoreCase : CharCompare;
我收到错误:
无法确定条件表达式的类型,因为“方法组”和“方法组”之间没有隐式转换
我可以使用常规 if ... else
语句来执行此分配,并且效果很好。但我不明白为什么我不能使用更紧凑的版本,也不明白错误消息。有谁知道这个错误的含义?
I've created a delegate and two matching methods.
private delegate bool CharComparer(char a, char b);
// Case-sensitive char comparer
private static bool CharCompare(char a, char b)
{
return (a == b);
}
// Case-insensitive char comparer
private static bool CharCompareIgnoreCase(char a, char b)
{
return (Char.ToLower(a) == Char.ToLower(b));
}
When I try to assign either of these methods to a delegate using the following syntax (note that this code is in a static method of the same class):
CharComparer isEqual = (ignoreCase) ? CharCompareIgnoreCase : CharCompare;
I get the error:
Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'
I can use a regular if ... else
statement to do this assignment and it works just fine. But I don't understand why I can't use the more compact version and I don't understand the error message. Does anyone know the meaning of this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
条件运算符中的类型在赋值之前解析,因此编译器无法使用赋值中的类型来解析条件运算符。
只需将其中一个操作数转换为
CharComparer
即可让编译器知道使用该类型:The types in the conditional operator is resolved before the assignment, so the compiler can't use the type in the assignment to resolve the conditional operator.
Just cast one of the operands to
CharComparer
so that the compiler know to use that type:尝试以下操作:
Try following: