使用 ? 分配委托时出错? : 语法

发布于 2024-10-19 03:31:11 字数 697 浏览 5 评论 0原文

我创建了一个委托和两个匹配方法。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漫漫岁月 2024-10-26 03:31:11

条件运算符中的类型在赋值之前解析,因此编译器无法使用赋值中的类型来解析条件运算符。

只需将其中一个操作数转换为 CharComparer 即可让编译器知道使用该类型:

CharComparer isEqual = ignoreCase ? (CharComparer)CharCompareIgnoreCase : CharCompare;

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:

CharComparer isEqual = ignoreCase ? (CharComparer)CharCompareIgnoreCase : CharCompare;
唐婉 2024-10-26 03:31:11

尝试以下操作:

CharComparer isEqual = (ignoreCase) ? new CharComparer(CharCompareIgnoreCase) : new CharComparer(CharCompare);

Try following:

CharComparer isEqual = (ignoreCase) ? new CharComparer(CharCompareIgnoreCase) : new CharComparer(CharCompare);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文