从 .net dll 导入的 类 运算符

Operators for classes imported from .net dlls

我正在尝试使用 Haxe 为 Unity 或 Godot 等游戏引擎编写脚本。

在这两种情况下,我都无法写出像

这样的行
Translate(dir * 100.0);

其中 dir 是从 Godot 的 .net dll 导入的 Vector2。统一。

到目前为止我找到的可行替代方案是

Translate(Vector2.op_Multiply(dir, 100.0));

乍一看似乎是 hxcs 模块中的错误,但经过一些研究后,它似乎是 Haxe 类型系统的限制。

另一种选择是使用抽象类型来重载运算符,从而产生如下代码:

Translate(new Vector2WithOps(dir) * 100.0);

所以我的问题是:有没有办法绕过显式转换为抽象类型?

从直觉上看,Haxe 似乎应该能够在从 C# 导入时自动应用运算符,并且它应该能够推断出乘法所需的类型并隐式执行到抽象类型的转换。我知道有技术原因导致两者至少都很难,但我仍然希望有一种我还没有见过的方法。

So my question is: is there a way to get around the explicit cast to the abstract type?

是的,摘要允许定义 implicit casts。您可以简单地将 from Vector2 to Vector2 添加到声明中:

abstract Vector2WithOps(Vector2) from Vector2 to Vector2 {}

这并不能神奇地使 dir * 100.0 之类的东西起作用,但是 - 您仍然需要一种方法来触发 dirVector2WithOps 的转换,例如通过分配它到类型为:

的变量
var dirWithOps:Vector2WithOps = dir;

还有一种叫做type check的特殊语法来触发转换:

(dir : Vector2WithOps)

最终,最方便的选择是确保您已经开始使用 Vector2WithOps。只要您在自己的代码中创建新实例,这种方法就可以工作,但是当从本机 API 返回一个实例时,效果就不那么好了。这让我想起了一个 Haxe 问题,考虑允许运算符通过 static extensions, which would be quite useful here: #2803

重载