运算符功能 +有两个隐式转换不起作用
我正在尝试将一些部分从 ginac (www.ginac.de) 移植到 C#。但我遇到了这个:
class Program {
static void Main(string[] args) {
symbol s = new symbol();
numeric n = new numeric();
ex e = s + n; // "Operator + doesn't work for symbol, numeric"
}
}
class ex {
//this should be already be sufficient:
public static implicit operator ex(basic b) {
return new ex();
}
//but those doesn't work as well:
public static implicit operator ex(numeric b) {
return new ex();
}
public static implicit operator ex(symbol b) {
return new ex();
}
public static ex operator +(ex lh, ex rh) {
return new ex();
}
}
class basic {
}
class symbol : basic {
}
class numeric : basic {
}
正确的顺序应该是:隐式转换符号->基本->ex,然后数字->基本->ex,然后使用 ex 运算符+(ex,ex) 函数。
隐式转换函数和运算符函数的查找按什么顺序完成? 有什么办法解决这个问题吗?
I'm trying to port some parts from ginac (www.ginac.de) to C#. But I encountered this:
class Program {
static void Main(string[] args) {
symbol s = new symbol();
numeric n = new numeric();
ex e = s + n; // "Operator + doesn't work for symbol, numeric"
}
}
class ex {
//this should be already be sufficient:
public static implicit operator ex(basic b) {
return new ex();
}
//but those doesn't work as well:
public static implicit operator ex(numeric b) {
return new ex();
}
public static implicit operator ex(symbol b) {
return new ex();
}
public static ex operator +(ex lh, ex rh) {
return new ex();
}
}
class basic {
}
class symbol : basic {
}
class numeric : basic {
}
The correct order should be: implicitly cast symbol->basic->ex, then numeric->basic->ex and then use the ex operator+(ex,ex) function.
In which order is the lookup for implicit casting functions and operator functions done?
Is there any way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于
运算符+
根据 MSDN,如果
operator +
方法中的参数都不属于编写该方法的类类型,则编译器会抛出错误。 文档链接。此代码将起作用,因为您至少将其中一个参数转换为
ex
类型:The problem is with the
operator +
According to MSDN, the compiler throws error if none of the parameter in
operator +
method is of class type in which the method is written. Link to documentation.This code will work because you are converting at least one of the parameters to
ex
type:将第一个操作数转换为“ex”。 + 运算符的第一个操作数不会被隐式转换。您需要使用显式强制转换。
+ 运算符实际上从第一个操作数确定其类型,在您的情况下是符号。当第一个操作数是 ex 时,ex+ex 将尝试第二个操作数的隐式转换。
Cast the first operand to "ex". The first operand of the + operator will not be implicitly cast. You need to use an explicit cast.
The + operator actually determines its type from the first operand, which is symbol in your case. When the first operand is an ex, then the ex+ex will attempt the implicit cast of the second operand.