ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
和不安全转换(第5.23.1节)不同,一个失败的转换的运行时行为在安全转换中被定义: > Unlike unsafe casts(5.23.1),the runtime behavior in case of a failing cast is defined for safe casts: ~~~ class Base { public function new() { } } class Child1 extends Base {} class Child2 extends Base {} class Main { public static function main() { var child1:Base = new Child1(); var child2:Base = new Child2(); cast(child1, Base); // Exception: Class cast error cast(child1, Child2); } } ~~~ 在这个例子中,我们首先转换一个Child1类的实例为Base,因为Child1是一个Base的子类(第2.3.2节),所以转换成功。然后尝试转换同样的类实例为 Child2,这是不被允许的,因为Child2的实例并不是Child1类型的。 > In this example we first cast a class instance of type Child1 to Base,which succeeds because Child1 is a child class (2.3.2) of Base. We then try to cast the same class instance to Child2, which is not allowed because instances of Child2 are not instances of Child1. Haxe编译器保证一个String类型的异常,在这种情况被抛出(第5.22节)。这个异常可以使用 try/catch 块捕捉到。 > The Haxe compiler guarantees that an exception of type String is thrown(5.22) in this case. This exception can be caught using a try/catch block (5.18). 安全转换有一个运行时的开销。理解编译器已经发生了类型检查是很重要的,所以添加手动的检查是冗余的,例如,使用 Std.is 。预期的使用是try安全转换,然后捕捉String类型的异常。 > Safe casts have a runtime overhead. It is important to understand that the compiler already generates type checks,so it is redundant to add manual checks,e.g. usingStd.is. The intended usage is to try the safe cast and catch the String exception.