C# this的五种用法

来源:互联网 发布:手机淘宝店铺怎么登陆 编辑:程序博客网 时间:2024/04/30 13:40
1.this的第一种用法:限定被参数隐藏的实例成员,如下例代码
public class Test
{
private int hour;

public void SomeMethod(int hour)
{
this.hour = hour;
}        
}
this.hour 代表的是当前实例的成员hour , 而hour代表的是SomeMethod的形参hour

2. this的第二种用法:把当前对象作为参数传给另一个方法,如下例代码
class myClass
{
public void Foo(OtherClass otherObject)
{
otherObject.Bar(this);
}
}

public class OtherClass
{
public void Bar(Object obj)
{
}
}
在myClass.Foo方法中,调用了OtherClass实例的Bar方法,而Bar的参数则是当前实例myClass的引用。

3. this的第三种用法与索引器有关(后续会详细说明)

4. this的第四种用法是从一个重载构造方法中调用 另一个, 如下例代码:
class myClass
{
public myClass(int i)
{
Console.WriteLine(i);
//...
}

public myClass() : this(42)
//...
}
}
使用this(42)调用了public myClass(42)的构造方法。

5. this的第五种用法显式调用一个类的方法和成员, 如下例代码:
class myClass
{
private int i;
private int z;

public void Draw()
}

public void MyMethod(int y)
{
this.i = 3;
this.z = 7;
this.Draw();
}
}
在这种情况下,this引用的使用是多余的。

0 0