简体   繁体   English

如果(this!= null),这有用吗?

[英]Is this in any way useful if (this != null)?

I came across some tests that included code like this: 我遇到了一些测试,包括这样的代码:

if (this != null) {
    do something
}

Is this if clause of any use? 这是if条款有用吗? Is there a purpose I don't get that makes this useful? 是否有一个我没有得到的目的使这有用?

this在Java中永远不会为null ,因此这种代码永远不会有用。

In Java the this keyword can only be used in a non-static method of a class. 在Java中, this关键字只能用于类的非静态方法。

Thus, if you are ever running code in the method, this cannot ever be null because you are guaranteed to have an instance of that object, otherwise the method would have never been able to be called. 因此,如果你曾经在方法中运行的代码, this可能永远不会成为null ,因为你都保证有一个对象实例,否则该方法将一直无法被调用。

The programmer was looking for a fancier way to write: 程序员正在寻找一种更好的写作方式:

if (true) {

}

You can't use "this" in a static environment that is the only place where "this" could be null. 你不能在静态环境中使用“this”,这是“this”可能为null的唯一地方。

You can call a static method or variable without an object, without an instance. 没有实例,可以在没有对象的情况下调用静态方法或变量。 "this" points to the current instance of the class. “this”指向班级的当前实例。 You can only use "this" if you have an object, so it will never be null. 如果你有一个对象,你只能使用“this”,所以它永远不会为null。

I'm a pretty clueless programmer, so don't believe a word I say (and correct me if I'm wrong!), but it calls to mind cogito ergo sum -- I think, therefore I am. 我是一个相当无能的程序员,所以不要相信我说的一句话(如果我错了就纠正我!),但它会让人想起cogito ergo sum - 我想,因此我是。 Descartes called it "the first and the most certain which presents itself to whoever conducts his thoughts in order." 笛卡尔称之为 “第一个也是最确定的,它表现在任何按顺序进行思考的人身上”。 Similarly, that this != null seems to be (in Java, anyway, from the sound of it) among the most trivial conclusions code can reach. 同样地, this != null似乎是(在Java中,无论如何,从它的声音)代码中可以达到的最微不足道的结论。 Neat! 整齐!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM