C#表达式if语句,可能扩展吗? [英] C# Expressional if statements, possible expansion?
问题描述
大家好,我的问题是:如何直接执行一个函数或委托以及如何使用C#中的单个表达式返回语句从方法返回值
Hi guys i have a question which is : how to directly execute a function or delegate as well as returning a value from a method using one single Expressional return statement in C#
* For参考,我正在使用C#7
*For reference, I am using C#7
在这种情况下,我需要向用户返回一个已生成的对象,如下所示:
In this context I need to return to the user an Object which has been generated like this:
object obj = cmd.ExecuteScalar();
我还有一个日志记录功能,我想调用它:
I also have a logging function which I want to call:
DoLog(cmd.CommandText)
PS:我100%意识到,我可以使用一些if语句更简单的方式来无条件地实现此目标-我只是问是否有人可以为我提供最优雅的解决方案一个衬里
PS: I am 100% aware that I can achieve this non-conditionally using a couple of if statements in a much easier way - i'm simply asking if anyone can provide me with the most elegant "one liner" approach possible.
以下是条件返回表达式通常如何工作的标准示例
Here is a standard example of how conditional return expressions usually work
return (someBool)
? value1
: value2;
如果someBool为TRUE,这将返回'value1';
this will return 'value1' if someBool is TRUE;
基本上我的问题是我可以做这样的事情
Basically my question is can i do something like this
return (chkStatus)
? (obj & DoLog(cmd.CommandText))
: null;
为了回应一些建议我可以使用单个管道运算符分割收益,而您的建议是真诚的,我想您从未尝试过编译它们。
In response to some of you who have suggested that I can use a single pipe operator to split the return, while your suggestions are in good faith, I assume you never tried to compile them
可以作为类型:Object和Void无法直接比较,从而导致编译时错误。
If you had you would see that it doesn't work as the types: Object and Void are NOT directly comparable thus causing a compile time error.
我对更精致/更优雅的方法的要求仍然存在。
My request for a more refined / elegant method still stands.
推荐答案
您可以使用lambda来解决问题,但这并不是一个干净的语法:
You can work something out using lambda's, but it will not be a clean syntax:
return (chkStatus
? (Func<object>)(() => {
DoLog(cmd.CommandText);
return obj;
})
: () => null)();
这篇关于C#表达式if语句,可能扩展吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!