在ClearScript中重载运算符

帕特里克·贝尔

我试图利用自定义运算符对我的应用程序中的自定义类进行算术运算,该类ClearScript接口以下是我的示例自定义类的摘要:

public class Vector3 {
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }

    public Vector3(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static Vector3 operator +(Vector3 a, Vector3 b) {
        return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
    }
}

我的ClearScript引擎已正确初始化,我可以Vector3通过Javascript正确初始化对象,并相应地修改属性。

但是,如果我Vector3在Javascript环境中初始化2个对象,并尝试使用Javascript加法运算符,则最终会将加法运算符评估为字符串连接,而不是我的自定义运算符。

例:

var a = new Vector3(1, 1, 1);
var b = new Vector3(0, 2, -1);

var c = a + b;

print(typeof a); //returns "function" (which is correct)
print(typeof b); //returns "function" (which is also correct)

print(typeof c); //returns "string" (should return function)

该变量c仅包含string[object HostObject][object HostObject]),而不包含Vector3对象。

如何让Javascript引擎知道调用我的自定义运算符,而不是通过ClearScript使用默认Javascript运算符?

比特币

JavaScript的+运算符返回数字加法或字符串连接的结果。您不能超载。对象可以覆盖valueOf和/或toString影响操作数转换,但是无法覆盖操作本身。

如果您不能直接从JavaScript调用自定义运算符,请尝试添加一个将其包装的常规方法:

public Vector3 Add(Vector3 that) { return this + that; }

然后,在JavaScript中:

var c = a.Add(b);

它不那么优雅,但应该可以。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章