【问题标题】:Inline if to decide what function to put in a delegate does not work内联 if 决定将什么函数放入委托中不起作用
【发布时间】:2014-11-13 14:47:22
【问题描述】:

为什么第 16 行没有构建,而其余的却构建。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication7
{
    class Program
    {
        public static Boolean functionPicker = true;

        static void Main(string[] args)
        {
            Action func = SomeFunction;
            Action funcOther = SomeOtherFunction;
            Action chosenFunc = ((functionPicker == true) ? SomeFunction : SomeOtherFunction); //This is line 16
            if (functionPicker)
            {
                chosenFunc = SomeFunction;
            }
            else
            {
                chosenFunc = SomeOtherFunction;
            }

        }

        public static void SomeFunction()
        {

        }

        public static void SomeOtherFunction()
        {

        }
    }
}

【问题讨论】:

  • 第 16 行会产生什么错误?
  • You can't use the ternary (?:) operator there。把它变成一个正常的if/else。
  • @MatthewWatson 在您引用的问题中,Jon 准确地展示了如何做到这一点(提示:一次演员表)。
  • @decPL 我更喜欢亲自避免演员阵容。我认为人们过度使用 ?: 并最终得到可读性较差的代码。
  • @decPL 嗯,我永远不会同意使用强制转换比不使用强制转换更好 - 主要是因为您随后不必要地引入了运行时错误的可能性。即使给定的代码不会发生这样的错误,我宁愿根本没有这种可能性。我同意我的“不能”应该是“不应该(IMO)”——尽管现在编辑它为时已晚。 :)

标签: c# .net delegates action


【解决方案1】:

这是因为,在使用三元运算符a? b : c 的表达式中,必须有从bccb 的隐式转换。这是另一个例子:Implicit conversion issue in a ternary condition

在您的表达式中,((functionPicker == true) ? SomeFunction : SomeOtherFunction);SomeFunctionSomeOtherFunction 是方法组,方法组之间没有隐式转换。即b不能转换为cc也不能转换为b

但是,两个方法组都可以转换为不带参数且返回类型为 void 的委托,就像 Action 的情况一样。因此,如果您将b 转换为Action,那么将有一个从cb 的隐式转换,正如@decPL 所演示的那样。

【讨论】:

  • 我不明白的是,三元运算符需要能够从b c 隐式转换。为什么不单独从b -> ac -> a 获得?一定有这个潜在的机制/原因,我仍然失踪。引用 Jon Skeet 的话:“在某些方面,C# 的类型推断不能更强大是一种耻辱”。不过感谢您的回答!它肯定有助于解决它并在将来避免它。
  • @MikedeKlerk a 是一个布尔表达式。您可能是指将分配结果的变量。但是请注意,这是一个完全不同的表达式 - 三元表达式及其结果类型是在赋值表达式之前之前自行计算的。
【解决方案2】:

编译器在尝试确定三元运算符表达式的类型时遇到问题,请尝试明确指定它:

Action chosenFunc = functionPicker ? (Action)SomeFunction : SomeOtherFunction;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多