2010-10-23 29 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 
    } 
} 
相關問題