为什么不能在 C# 中重载“=”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/599367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can '=' not be overloaded in C#?
提问by
I was wondering, why can't I overload '=' in C#? Can I get a better explanation?
我想知道,为什么我不能在 C# 中重载“=”?我能得到更好的解释吗?
采纳答案by David Rodríguez - dribeas
Memory managed languages usually work with references rather than objects. When you define a class and its members you are defining the object behavior, but when you create a variable you are working with references to those objects.
内存管理语言通常使用引用而不是对象。当您定义一个类及其成员时,您正在定义对象行为,但是当您创建一个变量时,您正在使用对这些对象的引用。
Now, the operator = is applied to references, not objects. When you assign a reference to another you are actually making the receiving reference point to the same object that the other reference is.
现在,运算符 = 应用于引用,而不是对象。当您将引用分配给另一个引用时,您实际上是在使接收引用指向另一个引用所在的同一对象。
Type var1 = new Type();
Type var2 = new Type();
var2 = var1;
In the code above, two objects are created on the heap, one referred by var1 and the other by var2. Now the last statement makes the var2 reference point to the same object that var1 is referring. After that line, the garbage collector can free the second object and there is only one object in memory. In the whole process, no operation is applied to the objects themselves.
在上面的代码中,在堆上创建了两个对象,一个由 var1 引用,另一个由 var2 引用。现在最后一条语句使 var2 引用指向 var1 所引用的同一对象。在那一行之后,垃圾收集器可以释放第二个对象,并且内存中只有一个对象。在整个过程中,没有对对象本身进行任何操作。
Going back to why = cannot be overloaded, the system implementation is the only sensible thing you can do with references. You can overload operations that are applied to the objects, but not to references.
回到为什么 = 不能重载,系统实现是您可以对引用做的唯一明智的事情。您可以重载应用于对象的操作,但不能重载应用于引用的操作。
回答by mqp
I don't think there's any really particular single reason to point to. Generally, I think the idea goes like this:
我认为没有任何真正特别的单一理由可以指出。一般来说,我认为这个想法是这样的:
If your object is a big, complicated object, doing something that isn't assignment with the
=
operator is probably misleading.If your object is a small object, you may as well make it immutable and return new copies when performing operations on it, so that the assignment operator works the way you expect out of the box (as
System.String
does.)
如果您的对象是一个大而复杂的对象,那么做一些不是用
=
运算符赋值的事情可能会产生误导。如果您的对象是一个小对象,您也可以使其不可变并在对其执行操作时返回新副本,以便赋值运算符以您期望的开箱即用方式工作(就像
System.String
那样)。
回答by markt
If you overloaded '=' you would never be able to change an object reference after it's been created. ... think about it - any call to theObjectWithOverloadedOperator=something inside the overloaded operator would result in another call to the overloaded operator... so what would the overloaded operator really be doing ? Maybe setting some other properties - or setting the value to a new object (immutability) ? Generally not what '=' implies..
如果您重载了 '=',则在创建对象引用后,您将永远无法更改该对象引用。... 想一想 - 在重载运算符中对 theObjectWithOverloadedOperator=something 的任何调用都会导致对重载运算符的另一个调用......那么重载运算符到底在做什么?也许设置一些其他属性 - 或者将值设置为新对象(不变性)?通常不是 '=' 所暗示的..
You can, however, override the implicit & explicit cast operators: http://www.blackwasp.co.uk/CSharpConversionOverload.aspx
但是,您可以覆盖隐式和显式转换运算符:http: //www.blackwasp.co.uk/CSharpConversionOverload.aspx
回答by Tanveer Badar
One possible explanation is that you can't do proper reference updates if you overload assignment operator. It would literally screw up semantics because when people would be expecting references to update, your = operator may as well be doing something else entirely. Not very programmer friendly.
一种可能的解释是,如果重载赋值运算符,则无法进行适当的引用更新。它实际上会搞砸语义,因为当人们期望引用更新时,您的 = 运算符也可能完全做其他事情。对程序员不是很友好。
You can use implicit and explicit to/from conversion operators to mitigate some of the seeming shortcomings of not able to overload assignment.
您可以使用隐式和显式 to/from 转换运算符来减轻无法重载赋值的一些表面上的缺点。
回答by Learning
It's allowed in C++ and if not careful , it can result in a lot of confusion and bug hunting.
它在 C++ 中是允许的,如果不小心,可能会导致很多混乱和错误搜索。
This article explains this in great detail.
这篇文章非常详细地解释了这一点。
回答by Daniel Earwicker
You can overload assignment in C#. Just not on an entire object, only on members of it. You declare a property with a setter:
您可以在 C# 中重载赋值。只是不在整个对象上,只在它的成员上。您使用 setter 声明一个属性:
class Complex
{
public double Real
{
get { ... }
set { /* do something with value */ }
}
// more members
}
Now when you assign to Real
, your own code runs.
现在,当您分配给 时Real
,您自己的代码就会运行。
The reason assignment to an object is not replaceable is because it is already defined by the language to mean something vitally important.
给对象赋值的原因是不可替换的,因为它已经被语言定义为意味着一些非常重要的东西。
回答by Peter Wone
Because shooting oneself in the foot is frowned upon.
因为用脚射击自己是不受欢迎的。
On a more serious note one can only hope you meant comparison rather than assignment. The framework makes elaborate provision for interfering with equality/equivalence evaluation, look for "compar" in help or online with msdn.
更严肃地说,人们只能希望你的意思是比较而不是分配。该框架详细规定了干扰平等/等效评估,在帮助中或在线与 msdn 中查找“比较”。
回答by pyon
Actually, overloading operator =
would make sense if you could define classes with value semantics and allocate objects of these classes in the stack. But, in C#, you can't.
实际上,operator =
如果您可以定义具有值语义的类并在堆栈中分配这些类的对象,那么重载是有意义的。但是,在 C# 中,你不能。
回答by Tomek Szpakowicz
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.
在 C# 中 = 将对象引用分配给变量。所以它对变量和对象引用进行操作,而不是对象本身。根据对象类型重载它是没有意义的。
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?
在 C++ 中,定义 operator= 对那些可以在例如堆栈上创建实例的类有意义,因为对象本身存储在变量中,而不是对它们的引用。因此,定义如何执行此类分配是有意义的。但即使在 C++ 中,如果您有一组通常通过指针或引用使用的多态类,您通常通过将 operator= 和复制构造函数声明为私有(或从 boost::noncopyable 继承)来明确禁止像这样复制它们,因为与您不在 C# 中重新定义 = 的原因完全相同。简单地说,如果你有类 A 的引用或指针,你真的不知道它是指向类 A 的实例还是指向 A 的子类的类 B。那么你真的知道在这种情况下如何执行 = 吗?
回答by supercat
Being able to define special semantics for assignment operations would be useful, but only if such semantics could be applied to all situations where one storage location of a given type was copied to another. Although standard C++ implements such assignment rules, it has the luxury of requiring that all types be defined at compile time. Things get much more complicated when Reflection and and generics are added to the list.
能够为赋值操作定义特殊的语义会很有用,但前提是这种语义可以应用于将给定类型的一个存储位置复制到另一个存储位置的所有情况。尽管标准 C++ 实现了这样的赋值规则,但它要求在编译时定义所有类型。当反射和泛型被添加到列表中时,事情变得更加复杂。
Presently, the rules in .net specify that a storage location may be set to the default value for its type--regardless of what that type is--by zeroing out all the bytes. They further specify that any storage location can be copied to another of the same type by copying all the bytes. These rules apply to all types, including generics. Given two variables of type KeyValuePair<t1,t2>
, the system can copy one to another without having to know anything but the size and alignment requirements of that type. If it were possible for t1
, t2
, or the type of any field within either of those types, to implement a copy constructor, code which copied one struct instance to another would have to be much more complicated.
目前,.net 中的规则指定存储位置可以设置为其类型的默认值 - 无论该类型是什么 - 通过将所有字节清零。它们进一步指定可以通过复制所有字节将任何存储位置复制到另一个相同类型的位置。这些规则适用于所有类型,包括泛型。给定两个 type 变量KeyValuePair<t1,t2>
,系统可以将一个变量复制到另一个变量,而无需知道该类型的大小和对齐要求。如果有可能的t1
,t2
或类型的任何领域内的任何类型的,实现一个拷贝构造函数,它复制一个结构实例到另一个将不得不更加复杂的代码。
That's not to say that such an ability offer some significant benefits--it's possible that, were a new framework being designed, the benefits of custom value assignment operators and default constructors would exceed the costs. The costs of implementation, however, would be substantial in a new framework, and likely insurmountable for an existing one.
这并不是说这种能力提供了一些显着的好处——如果设计了一个新框架,自定义值赋值运算符和默认构造函数的好处可能会超过成本。然而,在新框架中实施成本将是巨大的,对于现有框架来说可能是无法克服的。