C# this的用法

文章转自http://blog.sina.com.cn/s/blog_96ea9c6f0101crhh.html

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)
    { 
        //...
    }
}

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引用的使用是多余的。


猜你喜欢

转载自blog.csdn.net/weixin_40225128/article/details/79913779