【发布时间】: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)”——尽管现在编辑它为时已晚。 :)