Applescript - 为什么我不能使用动态分配的 类?

Applescript - why can I not use classes which are dynamically assigned?

如果我可以在 Applescript 中执行顶部的程序,为什么我不能执行底部的 2 个程序?

set _class to string
return ({"o", "k"} as string)

这有效,但底部 2 无效。

set _class to string
return ({"o", "k"} as _class)

或者

set _class to string
return ({"o", "k"} as (class of "hello"))

程序不让我编译底部 2.

因为类是在编译时评估的,因此必须是静态的。

由于 AppleScript 的 as 运算符太垃圾了,您真正能做的就是定义自己的处理程序来为您执行所需的转换。 (而且由于 AS 处理程序本身并不是设计为作为对象传递的,因此您还需要将它们包装在脚本对象中。这一切都非常乏味。)

script StringCoercion
    on coerceValue(theValue)
        (* caution: to guarantee predictable behavior, always set
           TIDs to a known value before coercing an unknown value
           to a string, just in case that value is a list *)
        set AppleScript's text item delimiters to ""
        return theValue as string
    end
end

script ListCoercion
    on coerceValue(theValue)
        return theValue as list
    end
end

set _class to StringCoercion
return _class's coerceValue({"o", "k"})
--> "ok"

或者,如果您不需要那么大的灵活性,只需使用条件块:

set _class to string
set theValue to {"o", "k"}

if _class is string then
    return theValue as string
else if _class is list then
    return theValue as list
else ...

老实说,您对这些事情的思考越多,您就越能意识到 AppleScript 对于 [i]一切[/i] 不是自动化应用程序的东西是多么糟糕。不幸的是,Apple 提供的 AS 替代品对于自动化应用程序来说很糟糕,因此它几乎是 Hobson 的选择。

老实说,我能推荐的最好的办法是让你的 AS 代码尽可能简单、乏味和不聪明,希望它不太可能崩溃。