如何编写强类型 lambda 表达式?
我想在内联 if 语句中编写 lambda 表达式。 但内联 if 语句必须具有强类型结果。
MyType obj = someObj.IsOk ? null : () => {
MyType o = new MyType(intVal);
o.PropertyName = false;
return o;
};
当然,这是行不通的,因为 lambda 表达式不是强类型的。 我想到使用 Func
delegate 来使其成为强类型。
但是我如何在内联 if 中使用这个 Func<>
呢? 我是否必须在外部定义自己的函数并在内联 if 语句中使用它?
I want to write a lambda expression within an inline if statement. But inline if statement must have strong type results.
MyType obj = someObj.IsOk ? null : () => {
MyType o = new MyType(intVal);
o.PropertyName = false;
return o;
};
Of course this doesn't work, because lambda expression isn't strongly typed. I thought of using Func<intVal, MyType>
delegate, to make it strong type.
But how do I use this Func<>
inside inline if? Is it at all possible of would I have to define my own function outside and use it in inline if statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使使用更复杂的代码,您也可以使用对象初始值设定项表达式:
如果您确实想使用 lambda,您可以这样写:
然而,坦率地说,这是一场噩梦括号和强制转换。 您可以使用辅助方法使其变得更简单:
Even with the more complicated code, you can use an object initializer expression:
If you really want to use a lambda though, you could write:
However, this is frankly a nightmare of brackets and casts. You can make it simpler with a helper method:
它与此处 lambda 的输入无关。 您试图返回 null 或(不带参数并返回 MyType 的函数),但您告诉编译器该语句的结果不是函数,而只是 MyType。 我想你想做的是
It has nothing to do with the lambda's typing here. You are trying to return either
null
or (a function taking no arguments and returning a MyType) but you are telling the compiler that the result of that statement is not a function, but just a MyType. I think what you want to do is如果你有这样的事情......
你会得到错误......
其原因在此 SO thread< 中讨论/a>.
马克对于您尝试对代码示例执行的操作是正确的,除了您也可以像这样设置属性...
If you have something like this ...
You will get the error ...
The reason for that is discussed in this SO thread.
Mark is correct on what you're trying to do with the code sample, except you can set the property in like as well like this ...