C#Func和条件运算符

pon*_*tic 5 c#

重复

我可以做这个:

Func<CategorySummary, decimal> orderByFunc;
if (orderBy == OrderProductsByProperty.Speed)
     orderByFunc = x => x.Speed;
else
    orderByFunc = x => x.Price;
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样做:

Func<CategorySummary, decimal> orderByFunc = (orderBy == OrderProductsByProperty.Speed) ? x => x.Speed : x => x.Price;
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 6

条件运算符上的"类型推断"不够好,我收到了类似的消息

无法确定条件表达式的类型,因为'lambda expression'和'lambda expression'之间没有隐式转换

你可以随时在右手边明确表达

var o = true ? new Func<int,int>(x => 0) : new Func<int,int>(x => 1);
Run Code Online (Sandbox Code Playgroud)

无论如何,关于lambdas类型,类型推理和条件运算符如何相互作用,这只是一个小麻烦.