简体   繁体   English

如何编写强类型的lambda表达式?

[英]How to write strongly typed lambda expressions?

I want to write a lambda expression within an inline if statement. 我想在一个内联if语句中编写一个lambda表达式。 But inline if statement must have strong type results. 但是内联if语句必须具有强类型结果。

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. 当然这是行不通的,因为lambda表达式不是强类型的。 I thought of using Func<intVal, MyType> delegate, to make it strong type. 我想到了使用Func<intVal, MyType>委托使其成为强类型。

But how do I use this Func<> inside inline if? 但是,如果Func<>内如何使用此Func<>呢? Is it at all possible of would I have to define my own function outside and use it in inline if statement? 是否有可能我必须在外部定义自己的函数并在if语句内联中使用它?

It has nothing to do with the lambda's typing here. 这与lambda的输入无关。 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. 您试图返回null或(不带任何参数并返回MyType的函数),但您要告诉编译器该语句的结果不是函数,而只是MyType。 I think what you want to do is 我想你想做的是

MyType obj = someObj.IsOk ? null : new MyType(intVal);

Even with the more complicated code, you can use an object initializer expression: 即使使用更复杂的代码,也可以使用对象初始化器表达式:

MyType obj = someObj.IsOk ? null : new MyType(intVal) { ProName = false };

If you really want to use a lambda though, you could write: 如果确实要使用lambda,则可以编写:

MyType obj = someObj.IsOk ? null : ((Func<MyType>) (() => {
   MyType o = new MyType(intVal);
   o.ProName = false;
   return o;
}))();

However, this is frankly a nightmare of brackets and casts. 但是,坦率地说,这是一场括号和演员表的噩梦 You can make it simpler with a helper method: 您可以使用辅助方法使其更简单:

public T Execute(Func<T> func)
{
    return func();
}

...

MyType obj = someObj.IsOk ? null : Execute(() => {
   MyType o = new MyType(intVal);
   o.ProName = false;
   return o;
});

If you have something like this ... 如果你有这样的事情...

  var obj = (someObj.IsOK) ? null : () => {
             return new MyType(intVal) { PropName =false }; }

You will get the error ... 您将收到错误信息...

"There is no explicit conversion between null and lambda expression." “在null和lambda表达式之间没有显式转换。”

The reason for that is discussed in this SO thread . 其原因在本SO线程中进行了讨论。

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 ... Mark可以正确处理您的代码示例,但您可以像这样设置属性...

var obj = someObj.IsOk ? null : new MyType(intVal) { PropName = false };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM