2010-10-23 28 views
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 { 
} 

正确的顺序应该是:隐式转换符号 - > basic-> EX,然后numeric-> basic->前,然后使用前运营商+(EX,EX)功能。

以何种顺序查找隐式​​转换函数和操作符函数? 有没有办法解决这个问题?

回答

1

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

+运算符实际上是从第一个操作数确定它的类型,这是你的情况中的符号。当第一个操作数是ex时,ex + ex将尝试隐式转换第二个操作数。

+0

我不认为这是第一和第二PARAM – CodesInChaos 2010-10-23 12:45:54

+0

不完全准确之间的不对称。 “+”运算符(以及所有二元运算符)根据左操作数*或右操作数确定运算符过载的类。但是否则你是正确的 - 它将不会从任务左侧的推断类型中获取。 – 2010-10-23 13:07:20

2

的问题是与operator + 根据MSDN,编译器会引发错误,如果没有在operator +方法中的参数的是其中所述方法被写入类型的。 Link to documentation

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 
    } 
} 
相关问题