C# 中的重载运算符 =
C# 中是否可以重载=运算符?
当我调用 = 时,我只想复制属性,而不是使左侧引用来引用另一个实例。
Is it possible to overload operator = in c#?
when i call =, i just want to copy properties, rather than making the left hand reference to refer another instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是否:
即使可能,我也不会推荐它。阅读代码的人不会认为赋值运算符有可能被重载。有了复制对象的方法就会清晰很多。
The answer is no:
And even if it was possible, I wouldn't recommend it. Nobody who reads the code is going to think that there's ANY possibility that the assignment operator's been overloaded. A method to copy the object will be much clearer.
您不能重载
=
运算符。此外,您尝试做的事情将完全改变运算符的语义,因此换句话说这是一个坏主意。如果您想提供复制语义,请提供
Clone()
方法。You can't overload the
=
operator. Furthermore, what you are trying to do would entirely change the operator's semantics, so in other words is a bad idea.If you want to provide copy semantics, provide a
Clone()
method.为什么不在对象中创建 .CopyProperties(ByVal yourObject As YourObject) 方法?
您使用内置对象吗?
Why not make a .CopyProperties(ByVal yourObject As YourObject) method in the object?
Are you using a built-in object?
我们可以重载 = 运算符,但不能直接重载。
这里,当您调用该运算符重载方法时,它正在调用 = 运算符本身将其转换为 int。你不能直接重载“=”,但这种代码方式的意思是一样的。
We can Overload = operator but not directly.
Here when you call that operator overloading method , it is calling = operator itself to convert that to int. You cannot directly overload "=" but this way of code means the same.