类?.调用方法()这种写法的解释
代码:
toolBlock?.Shutdown();这是 C# 的空条件调用。
等价于:
if (toolBlock != null) { toolBlock.Shutdown(); }意思是:如果当前toolBlock不为空,就调用它的Shutdown()方法;如果是null,就跳过,不报错。
?.叫空条件运算符,也叫null 条件调用。
这句:
toolBlock?.Shutdown();意思是:
如果 toolBlock 不是 null,就调用 Shutdown() 如果 toolBlock 是 null,就什么也不做等价于:
if (toolBlock != null) { toolBlock.Shutdown(); }为什么要有??
因为m_ToolBlocks这个列表里可能有空元素:
m_ToolBlocks = new List<ToolBlockThread> { toolBlock1, null, toolBlock3 };如果直接写:
toolBlock.Shutdown();当toolBlock == null时,就会报错:
NullReferenceException也就是“空引用异常”。
用:
toolBlock?.Shutdown();就能安全跳过空对象。
简单记:
对象?.方法()就是:
对象不为空才调用方法类似还有:
string name = user?.Name;意思是:
user 不为空就取 user.Name,否则返回 nullbool result = true; if (m_ToolBlocks != null) { foreach (ToolBlockThread toolBlock in m_ToolBlocks) { toolBlock?.Shutdown(); } }