C#FUNC键,条件运算符 [英] C# Func and Conditional Operator

查看:170
本文介绍了C#FUNC键,条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复



我可以这样做:

  Func键< CategorySummary,小数> orderByFunc; 
如果(ORDERBY == OrderProductsByProperty.Speed​​)
orderByFunc = X => x.Speed​​;
,否则
orderByFunc = X => x.Price;



为什么我不能做到这一点:

  Func键< CategorySummary,小数> orderByFunc =(排序依据== OrderProductsByProperty.Speed​​)? X => x.Speed​​:X => x.Price; 


解决方案

在条件运算符'类型推断'是不是很够好,我得到这样



的消息

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




您可以随时只是在右侧显 - 侧,一拉

 变种O =真的吗?新的函数功能:LT; INT,INT>(X = 0):新的Func键< INT,INT>(X => 1); 

在任何情况下,它只是关于一个小麻烦怎么类型lambda表达式,类型推断,以及有条件的运营商互动。


Duplicate

I can do this:

Func<CategorySummary, decimal> orderByFunc;
if (orderBy == OrderProductsByProperty.Speed)
     orderByFunc = x => x.Speed;
else
    orderByFunc = x => x.Price;

Why can't I do this:

Func<CategorySummary, decimal> orderByFunc = (orderBy == OrderProductsByProperty.Speed) ? x => x.Speed : x => x.Price;

解决方案

The 'type inference' on the conditional operator is not quite good enough, I get a message like

Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

you can always just be explicit on the right-hand-side, a la

var o = true ? new Func<int,int>(x => 0) : new Func<int,int>(x => 1);

In any case it's just a minor annoyance regarding how the types of lambdas, type inference, and the conditional operator interact.

这篇关于C#FUNC键,条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆