在 ClearScript 中重载运算符

Overloading operators in ClearScript

我正在尝试使用自定义运算符对我的应用程序中的自定义 classes 进行算术运算,该应用程序与 ClearScript 接口。下面是我的示例自定义片段 class:

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 引擎正确初始化,我可以通过 Javascript 正确初始化 Vector3 个对象,并相应地修改属性。

但是,如果我在 Javascript 环境中初始化 2 个 Vector3 对象,并尝试使用 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的+ operator returns the result of numeric addition or string concatenation. You can't overload it. Objects can override valueOf and/or toString影响操作数转换,但无法覆盖操作本身。

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

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

然后,在JavaScript中:

var c = a.Add(b);

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