1

我正在尝试将一些部分从 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 {
}

正确的顺序应该是:隐式转换 symbol->basic->ex,然后 numeric->basic->ex,然后使用 ex operator+(ex,ex) 函数。

隐式转换函数和运算符函数的查找按什么顺序完成?有没有办法解决?

4

2 回答 2

2

问题出在operator + 根据 MSDN,如果方法中的参数都不operator +是编写该方法的类类型,则编译器会抛出错误。链接到文档

class iii { //this is extracted from the link above.. this is not complete code.
public static int operator +(int aa, int bb) ...  // Error CS0563
// Use the following line instead:
public static int operator +(int aa, iii bb) ...  // Okay.
}

此代码将起作用,因为您正在将至少一个参数转换为ex类型:

class basic { }
class symbol : basic { }
class numeric : basic { }

class ex {
    public static implicit operator ex(basic b) {
        return new ex();
    }

    public static implicit operator basic(ex e) {
        return new basic();
    }

    public static ex operator + (basic lh, ex rh) {
        return new ex();
    }
}

class Program {
    static void Main(string[] args) {
        symbol s = new symbol();
        numeric n = new numeric();

        // ex e0 = s + n; //error!
        ex e1 = (ex)s + n; //works
        ex e2 = s + (ex)n; //works
        ex e3 = (ex)s + (ex)n; //works
    }
}
于 2010-10-23T12:13:22.583 回答
1

将第一个操作数转换为“ex”。+ 运算符的第一个操作数不会被隐式转换。您需要使用显式强制转换。

+ 运算符实际上从第一个操作数确定其类型,在您的情况下是符号。当第一个操作数是 ex 时,ex+ex 将尝试对第二个操作数进行隐式强制转换。

于 2010-10-23T11:30:35.693 回答