Why aren't assignment operators overloadable in VB.NET? [closed]

人盡茶涼 提交于 2020-01-02 03:44:08

问题


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 };
    }
}


来源:https://stackoverflow.com/questions/10282565/why-arent-assignment-operators-overloadable-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!