反转?操作者

Ego*_*hin 5 c#

是否有可能在C#中做这样的事情?

logger != null ? logger.Log(message) : ; // do nothing if null

要么

logger !?? logger.Log(message); // do only if not null

ito*_*son 8

不.你可以来的最近的可能是通过空对象设计:

(logger ?? NullLogger.Instance).Log(message);
Run Code Online (Sandbox Code Playgroud)

其中NullLogger.Instance是一个只记录其所有方法的记录器.(当然,如果您需要默认行为来执行某些操作而不是无操作,则可以替换合适的Logger.Default或其他任何内容而不是NullLogger.Instance.)


Lan*_*ney 7

你想要太聪明......只需使用if:

if(logged != null) logger.Log(message);
Run Code Online (Sandbox Code Playgroud)


Arn*_*psa 6

:)

if (logger!=null) logger.Log(message);
Run Code Online (Sandbox Code Playgroud)

不......不幸的是,这样的运营商不存在.