Difference between this and base [closed]

2019-01-25 06:26发布

I am interested to know the difference between this and base object in C#. What is the best practice when using them?

标签: c# this
8条回答
smile是对你的礼貌
2楼-- · 2019-01-25 06:53

Darin is right on. An example may also help. (There wasn't an example when I initially posted. Now there is.)

class Base {

    protected virtual void SayHi() {
        Console.WriteLine("Base says hi!");
    }

}

class Derived : Base {

    protected override void SayHi() {
        Console.WriteLine("Derived says hi!");
    }

    public void DoIt() {
        base.SayHi();
        this.SayHi();
    }
}

The above prints "Base says hi!" followed by "Derived says hi!"

查看更多
老娘就宠你
3楼-- · 2019-01-25 06:53

lets say you have code like this

class B extends A {

    public B () {
        // this will refer to the current object of class B
        // base will refer to class A
    }

}

Note: The syntax of code is in java but it is self explanatory.

查看更多
淡お忘
4楼-- · 2019-01-25 06:53

this refers to the current class instance.

base refers to the base class of the current instance, that is, the class from which it is derived. If the current class is not explicitly derived from anything base will refer to the System.Object class (I think).

查看更多
We Are One
5楼-- · 2019-01-25 06:59

this represents the current class instance while base the parent. Example of usage:

public class Parent
{
    public virtual void Foo()
    {
    }
}

public class Child : Parent
{
    // call constructor in the current type
    public Child() : this("abc")
    {
    }

    public Child(string id)
    {
    }

    public override void Foo()
    { 
        // call parent method
        base.Foo();
    }
}
查看更多
Explosion°爆炸
6楼-- · 2019-01-25 07:08

base - is used to access members of the base class from within a derived class

this - refers to the current instance of the class and inherited

class BaseClass
{
    public string BaseAttr { get; set; }
}
class A : BaseClass
{
    public string Attr { get; set; }
    public void Method()
    {
        this.Attr = "ok";
        this.BaseAttr = "base ok";
        base.BaseAttr = "ok";
        base.Attr = "unavailable"; //!
    }
}
查看更多
Anthone
7楼-- · 2019-01-25 07:09

this refers to any object that is currently being used. Base refers to a base class generally speaking.

If the object is of the base then in that case this can refer to the base object also.

查看更多
登录 后发表回答