冗余的可选链
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
}要修复这些警告,请将冗余的可选查找替换为非可选查找:
© 2026 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.