Roku开发中函数返回值类型不匹配问题求助
Roku开发:处理函数多类型返回的类型不匹配问题
问题分析
你遇到的类型不匹配错误,根源是FindCurrDateObject函数声明返回Object类型,但实际可能返回整数0;调用时直接访问title/text属性,当返回值是0时自然会触发错误。
解决方案
方案1:统一函数返回类型(推荐)
修改函数,让它始终返回Object类型或者invalid(Roku中的空值),避免混合类型返回。这样调用时只需先判断是否为有效对象即可:
修改后的函数代码:
function FindCurrDateObject(date as Integer) as Object m.date = CreateObject("roDateTime") for each item in m.global.itemArray now = m.date.AsSeconds() if now >= date then return { title: item.title, text: item.text } end if end for // 遍历完没找到匹配项,返回invalid return invalid end function
调用代码调整:
m.CurrDateObject = FindCurrDateObject(m.itemContent.date) if m.CurrDateObject <> invalid then ?"title :" m.CurrDateObject.title ?"text :" m.CurrDateObject.text else ?"未找到匹配的日期对象" end if
方案2:调用时先判断返回值类型
如果不想修改原函数(不推荐,混合类型返回属于不良编码实践,会增加维护难度),可以在调用时先检查返回值的类型,再决定是否访问属性:
m.CurrDateObject = FindCurrDateObject(m.itemContent.date) if type(m.CurrDateObject) = "roAssociativeArray" then ?"title :" m.CurrDateObject.title ?"text :" m.CurrDateObject.text else ?"未找到匹配的日期对象" end if
补充说明
Roku的BrightScript是强类型语言,函数返回类型保持一致是最佳实践,混合返回不同类型会埋下潜在bug,优先推荐方案1统一返回类型。
内容的提问来源于stack exchange,提问作者Nikunj Chaklasiya
相关产品推荐
相关产品推荐

