为什么java中不允许赋值给'this'? [英] Why is assignment to 'this' not allowed in java?

查看:648
本文介绍了为什么java中不允许赋值给'this'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从编译器得到的错误是赋值的左侧必须是变量。我的用例是深度复制,但并不是真正相关。

The error I get from the compiler is "The left hand side of an assignment must be a variable". My use case is deep copying, but is not really relevant.

在C ++中,可以分配给 * this

In C++, one can assign to *this.

问题不在于如何绕过这个的转让。这很简单,但是决定不让这个变量的背后有什么理由。

The question is not how to circumvent assignment to this. It's very simple, but rather what rationale is there behind the decision not to make this a variable.

是技术或概念的原因?

Are the reasons technical or conceptual?

我的猜测到目前为止 - 在随机方法中重建Object的可能性容易出错(概念性),但技术上可行。

My guess so far - the possibility of rebuilding an Object in a random method is error-prone (conceptual), but technically possible.

编辑请限制因为java规格如此说明的变体。我想知道决定的原因

EDIT Please restrain from variations of "because java specs say so". I would like to know the reason for the decision

推荐答案


在C ++中,可以分配给 * this

是的,但你不能在C ++中做 this = something ,我实际上认为这与你所询问的内容更接近在Java方面这里。

Yes, but you can't do this = something in C++, which I actually believe is a closer match for what you're asking about on the Java side here.


[...]决定不做的理由是什么这个一个变量。

我想说清晰度/可读性。

I would say clarity / readability.

这个被选为保留字,可能因为它没有作为显式参数传递一种方法。使用它作为普通参数并能够为其重新赋值,会严重损害可读性。

this was chosen to be a reserved word, probably since it's not passed as an explicit argument to a method. Using it as an ordinary parameter and being able to reassign a new value to it, would mess up readability severely.

事实上,很多人认为你不应该改变因此,参数变量完全存在。

In fact, many people argue that you shouldn't change argument-variables at all, for this very reason.


原因是技术性的还是概念性的?

Are the reasons technical or conceptual?

我认为主要是概念性的。但是会出现一些技术怪癖。如果你可以将值重新分配给这个,你可以完全隐藏局部变量后面的实例变量。

Mostly conceptual I would presume. A few technical quirks would arise though. If you could reassign a value to this, you could completely hide instance variables behind local variables for example.


我的猜测到目前为止 - 以随机方法重建对象的可能性容易出错(概念性),但技术上可行。

My guess so far - the possibility of rebuilding an Object in a random method is error-prone (conceptual), but technically possible.

我不确定我是否完全理解这个陈述,但是,容易出错可能是决定将其作为关键字的主要原因不是变量。

I'm not sure I understand this statement fully, but yes, error prone is probably the primary reason behind the decision to make it a keyword and not a variable.

这篇关于为什么java中不允许赋值给'this'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆