2010-06-10 50 views

回答

4

它通常被認爲是一個壞主意,用含蓄的運營商,因爲他們畢竟是隱式和你背後運行。調試運算符重載的代碼是一場噩夢。也就是說,像這樣的東西:

public class Complex 
{ 
    public int Real { get; set; } 
    public int Imaginary { get; set; } 

    public static implicit operator Complex(int value) 
    { 
     Complex x = new Complex(); 
     x.Real = value; 
     return x; 
    } 
} 

你可以使用:

Complex complex = 10; 

或你所能重載+操作

public static Complex operator +(Complex cmp, int value) 
{ 
    Complex x = new Complex(); 
    x.Real = cmp.Real + value; 
    x.Imaginary = cmp.Imaginary; 
    return x; 
} 

,並使用類似的代碼

complex +=5; 
+0

老實說,我已經閱讀MSDN的impicit操作符,但由於某些錯誤,我無法實現它。現在我測試它的代碼,它的工作原理。謝謝 – Freshblood 2010-06-10 16:24:24

+0

我很高興我的幫助。 – SWeko 2010-06-10 17:22:51

3

創建一個隱含的操作:

http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

例如:

public struct MyStruct // I assume this is what you meant, since you mention struct in your title, but use MyClass in your example. 
{ 
    public MyClass(int i) { val = i; } 
    public int val; 
    // ...other members 

    // User-defined conversion from MyStruct to double 
    public static implicit operator int(MyStruct i) 
    { 
     return i.val; 
    } 
    // User-defined conversion from double to Digit 
    public static implicit operator MyStruct(int i) 
    { 
     return new MyStruct(i); 
    } 
} 

「這是個好主意嗎?」是有爭議的。隱式轉換傾向於打破程序員接受的標準;一般不是一個好主意。但是,如果你正在做一個大型的價值圖書館,那麼它可能是一個好主意。

1

是的,這裏有一個簡單的例子...

public struct MyCustomInteger 
    { 
    private int val; 
    private bool isDef; 
    public bool HasValue { get { return isDef; } } 
    public int Value { return val; } } 
    private MyCustomInteger() { } 
    private MyCustomInteger(int intVal) 
    { val = intVal; isDef = true; } 
    public static MyCustomInteger Make(int intVal) 
    { return new MyCustomInteger(intVal); } 
    public static NullInt = new MyCustomInteger(); 

    public static explicit operator int (MyCustomInteger val) 
    { 
     if (!HasValue) throw new ArgumentNullEception(); 
     return Value; 
    } 
    public static implicit operator MyCustomInteger (int val) 
    { return new MyCustomInteger(val); } 
    } 
+0

難道你不是指'隱式'而不是'顯式'嗎? – ChrisF 2010-06-10 15:00:39

+0

哪個?兩者都存在......隱含的意思是,當沒有機會演員可能失敗時......明確的是當它可能失敗時...... – 2010-06-10 15:04:51

+0

啊,我的錯誤。我期待這兩者都是「隱含的」,如果你不經過檢查就可以兩種方式進行投射。 – ChrisF 2010-06-10 16:51:08

相關問題