2012-04-23 102 views
6

爲什麼在VB.NET中賦值運算符(+ =, - =,* =,/ =)不可重載?爲什麼在VB.NET中賦值運算符不可重載?

+0

@ Mr.Disappointment - 是啊,發現自己。你能否指出在那篇文章中它說了爲什麼賦值運算符不可重載? – user1351569 2012-04-23 14:36:03

+0

@ Mr.Disappointment - 也許你會讀一些我錯過的東西。 – user1351569 2012-04-23 14:44:46

+0

添加了一些關於隱式/顯式轉換器的東西,可能會幫助您嘗試執行任何操作。 – Alain 2012-04-23 15:00:24

回答

10

也許this是他們的推理:

感謝您的建議!我們不允許您爲某個類型重載 賦值運算符,因爲目前沒有辦法確保其他語言或.NET Framework本身將賦值 賦值運算符。唯一的選擇是限制哪些類型會使賦值運算符過載,但我們認爲這會限制性太強,以至於無法使用。

謝謝!保羅·維克技術負責人,VB

有一些所謂的「窄化」和「拓寬」,它允許你從一種類型的定義明確的和隱含轉換到另一種,即

Dim y as MyClass1 
Dim x as MyClass2 = y 

但是,這並不讓改變賦值操作符來分配同一個類的實例,只轉換其他類。

參見How to: Define a Conversion Operator

Class MyClass1 
    Public Shared Widening Operator CType(ByVal p1 As MyClass1) As MyClass2 

    End Operator 
End Class 

Same in C#

+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

賦值運算不能被重載,但+ =,例如,使用+評價,其可以被重載。

=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof

這些運算符不能被重載。

與同conversion operators

struct MyType1 
{ 
    ... 
    public static explicit operator MyType1(MyType2 src) //explicit conversion operator 
    { 
     return new MyType1 { guts = src.guts }; 
    } 
} 
+0

在2004年關閉「無法修復」票 - rofl。希望他們能夠重新考慮這個建議。 – Alain 2012-04-23 14:41:26

+0

是嗎? http://stackoverflow.com/questions/292676/is-there-a-workaround-for-overloading-the-assignment-operator-in-c – Alain 2012-04-23 14:45:47

+1

C#不支持運算符重載:http://msdn.microsoft。 COM/EN-US /庫/ 8edha89s.aspx。解決方法是重載運算符'+',因爲+ =使用它,但仍不能重載'='。 – Alain 2012-04-23 14:48:32