冗余可选链
此警告类别由 qmllint 拼写为[redundant-optional-chaining]
。
冗余可选链
发生了什么事?
有些查找在不必要的情况下使用了可选链。这种情况可能发生在查找枚举值时,或者在无法null
或undefined
的基础上执行查找时。
为什么这样做不好?
可选查找需要执行运行时检查,而常规查找则不需要。这些额外的指令不可能总是被确定为多余的,也不可能被工具优化掉。因此,它们会增加额外的运行时性能成本,使程序不必要地臃肿。
此外,警告还可能暗示可选查找是在链中错误的基础上执行的。更具体的示例请参见下一节。
示例
// Main.qml import QtQml QtObject { // Main will either be resolved and always work, or throw an exception or fail to compile enum E { A, B, C } property int i: Main?.A // A url cannot be null or undefined property url u: "" property string s: u?.toString() // Did you mean to make the second lookup optional? property int i: Safe?.Unsafe.i }
要修复这些警告,请将多余的可选查找替换为非可选查找:
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.