Kim*_*max 0 c# shorthand-if operators shorthand
检查布尔值是否为true时是否有简写形式?
例:
if (autoConnect) Connect();
Run Code Online (Sandbox Code Playgroud)
我们能做的
return IsOpen() ? true : false;
Run Code Online (Sandbox Code Playgroud)
但是我不能
autoConnect ? Connect();
Run Code Online (Sandbox Code Playgroud)
运行。有没有办法做到这一点?
您可以编写一个扩展方法:
public static void _(this bool b, Action ifTrue)
{
if (b) { ifTrue(); }
}
Run Code Online (Sandbox Code Playgroud)
那么你可以写:
autoConnect._(Connect);
Run Code Online (Sandbox Code Playgroud)
尽管显然这不是很可读,不建议这样做。