我正在尝试在我的应用程序中使用自定义运算符对自定义类进行算术运算,该应用程序与 ClearScript 接口(interface)。 。下面是我的示例自定义类的片段:
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
仅包含字符串
([object HostObject][object HostObject]
),而不是Vector3
对象。
如何让 Javascript 引擎知道调用我的自定义运算符,而不是使用 ClearScript 的默认 Javascript 运算符?
最佳答案
JavaScript 的 +
operator返回数字加法或字符串连接的结果。你不能重载它。对象可以覆盖 valueOf
和/或 toString
影响操作数转换,但无法覆盖操作本身。
如果您无法直接从 JavaScript 调用自定义运算符,请尝试添加一个普通方法来包装它:
public Vector3 Add(Vector3 that) { return this + that; }
然后,在 JavaScript 中:
var c = a.Add(b);
它不是那么优雅,但应该可以工作。
关于c# - ClearScript 中的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42458753/