C# this的五种用法

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值