Why can '=' not be overloaded in C#?

前端 未结 12 849
离开以前
离开以前 2020-12-30 00:49

I was wondering, why can\'t I overload \'=\' in C#? Can I get a better explanation?

12条回答
  •  难免孤独
    2020-12-30 01:33

    Because it doesn't really make sense to do so.

    In C# = assigns an object reference to a variable. So it operates on variables and object references, not objects themselves. There is no point in overloading it depending on object type.

    In C++ defining operator= makes sense for classes whose instances can be created e.g. on stack because the objects themselves are stored in variables, not references to them. So it makes sense to define how to perform such assignment. But even in C++, if you have set of polymorphic classes which are typically used via pointers or references, you usually explicitly forbid copying them like this by declaring operator= and copy constructor as private (or inheriting from boost::noncopyable), because of exactly the same reasons as why you don't redefine = in C#. Simply, if you have reference or pointer of class A, you don't really know whether it points to an instance of class A or class B which is a subclass of A. So do you really know how to perform = in this situation?

提交回复
热议问题