Why aren't assignment operators overloadable i

2019-04-27 07:10发布

问题:

Why aren't the assignment operators (+=, -=, *=, /=) overloadable in VB.NET?

回答1:

Perhaps this is their reasoning:

Thanks for the suggestion! We don't allow you to overload the assignment operator for a type because there is currently no way to ensure that other languages or the .NET Framework itself will honor the assignment operator. The only alternative is to restrict what types that overload the assignment operator can do, but we felt that this would be too restrictive to be generally useful.

Thanks! Paul Vick Technical Lead, VB

There's something called 'Narrowing' and 'Widening' which allows you to define explicit and implicit converters from one type to another, i.e.

Dim y as MyClass1
Dim x as MyClass2 = y

But that doesn't let change the assignment operator for assigning an instance of the same class, only converting other classes.

See 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#

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

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

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

These operators cannot be overloaded.

With the same conversion operators:

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