我试图在我的应用程序中的自定义类上利用自定义运算符进行算术运算,该应用程序与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引擎已正确初始化,我可以通过Javascript正确初始化Vector3对象,并相应地修改属性。
但是,如果我在Javascript环境中初始化两个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操作符?
发布于 2017-02-26 09:52:44
JavaScript的+ operator返回数字相加或字符串连接的结果。你不能超载它。对象可以覆盖valueOf和/或toString来影响操作数转换,但无法覆盖操作本身。
如果您不能直接从JavaScript调用您的自定义操作符,请尝试添加一个包装它的普通方法:
public Vector3 Add(Vector3 that) { return this + that; }然后,在JavaScript中:
var c = a.Add(b);它不是那么优雅,但它应该可以工作。
https://stackoverflow.com/questions/42458753
复制相似问题