#c# #lambda #c#-8.0 #switch-expression
#c# #лямбда #c #-8.0 #switch-выражение
Вопрос:
Я хочу использовать новый переключатель в своем коде, который для результата метода регистрирует и возвращает IActionResult
.
Я пытаюсь сделать что-то вроде этого:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString())); \return bool
return response switch
{
true => () =>
{
this._log.LogInformation("Write is complited");
return Ok();
},
false => () =>
{
this._log.LogInformation("Error in writing");
return BadRequest();
},
_ => () =>
{
throw new Exception("Unexpected error");
}
};
Но компилятор говорит мне cannot convert lambda expression to type 'IActionResult' because it is not a delegate type
.
Как я могу это исправить?
Ответ №1:
Проблема в том, что ваше выражение switch возвращает a, lambda expression
но содержащий метод ожидает IActionResult
. Чтобы устранить проблему, вам следует переписать оператор return, чтобы немедленно вызвать результат выражения switch:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));
return (response switch
{
// Here we cast lambda expression to Func<IActionResult> so that compiler
// can define the type of the switch expression as Func<IActionResult>.
true => (Func<IActionResult>) (() =>
{
this._log.LogInformation("Write is complited");
return Ok();
}),
false => () =>
{
this._log.LogInformation("Error in writing");
return BadRequest();
},
_ => () =>
{
throw new Exception("Unexpected error");
}
})(); // () - here we invoke Func<IActionResult>, the result of the switch expression.
На вашем месте я бы переписал этот код следующим образом, чтобы его было легче читать:
var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));
// Now additional braces or casts are not required.
Func<IActionResult> func = response switch
{
true => () =>
{
this._log.LogInformation("Write is complited");
return Ok();
},
false => () =>
{
this._log.LogInformation("Error in writing");
return BadRequest();
},
_ => () =>
{
throw new Exception("Unexpected error");
}
}
return func();