And*_*are 38
的this关键字是对当前对象的引用.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Run Code Online (Sandbox Code Playgroud)
考虑它的另一种方式是this关键字就像你用来引用自己的人称代词.其他语言对于相同的概念有不同的词.VB使用Me和Python约定(因为Python不使用关键字,只是每个方法的隐式参数)是要使用的self.
如果您要引用本质上属于您的对象,您可以这样说:
我的胳膊还是我的腿
把它想象this成一种类型说"我的"的方式.因此,伪代码表示如下所示:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*rdt 21
关键字this在不同的上下文中可能意味着不同的东西,这可能是您混淆的根源.
它可以用作对象引用,它引用调用当前方法的实例: return this;
它可以用作对象引用,引用当前构造函数正在创建的实例,例如访问隐藏字段:
MyClass(String name)
{
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
它可以用于从构造函数中调用aa类的不同构造函数:
MyClass()
{
this("default name");
}
Run Code Online (Sandbox Code Playgroud)
它可用于从嵌套类中访问封闭实例:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
关键字this是对当前对象的引用.最好用以下代码解释:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
Run Code Online (Sandbox Code Playgroud)
它没有被大量使用,除非你的地方有代码标准告诉你使用this关键字.它有一个常见的用途,那就是如果你遵循一个代码约定,你的参数名称与你的类属性相同:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
Run Code Online (Sandbox Code Playgroud)
正确使用this关键字是链构造函数(使构造对象在构造函数中保持一致):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
Run Code Online (Sandbox Code Playgroud)
此关键字在例如C#中的工作方式相同.
| 归档时间: |
|
| 查看次数: |
59792 次 |
| 最近记录: |