I have this piece of code:
public static void Debug(string workName, string message, string logcontext, string exMessage = "")
{
LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, logcontext, message + ": " + exMessage);
...
}
As you can see, the last parameter of the Debug method is optional ( string exMessage = ""
). That means that if I run this code as-is it will look fine if a exMessage arrived: "...message: exMessage"
However, If a exMessage wasn't provided, it will look like this: "...message: "
(Note the trailing :
).
Of course, this can easily be solved by using something like this:
if(!String.IsNullOrEmpty(exMessage)
{
...(...,message + ": " + exMessage);
}
else
{
...(...,message);
}
I want a more beautiful approach. Like if there is something in the lines of:
...(...(!exMessage -> ,message | else -> ,message + ": " + exMessage));
Is there some way of doing this in-line if-statement in C#? Can I use lambdas some how? (I'm super-new to the whole concept of lambdas)
您可以使用条件运算符
exMessage == "" ? message : message + ": " + exMessage
There is its called the ?: operator. You use it like this:
var logText = string.IsNullOrEmpty(exMessage) ? message : message + ": " + exMessage;
LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, logcontext, message + (!string.IsNullOrEmpty(exMessage) ? ": " : string.Empty) + exMessage);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.