C#中this和base关键字

this

this:指的是这个对象本身,主要用于:

  1. 在定义类时,写上this. 后vs会出现这个类中非静态的成员,智能提示。
  2. 一般在构造函数中使用,区分字段和局部变量
class Person
    {
        public string name;
        public Person(string name)
        {
            this.name = name;
        }
    }
  1. 用于在构造函数中调用两一个构造函数
class Person
    {
        public string name;
        public int age;
        public Person(string name)
        {
            this.name = name;
        }
        public Person(string name,int age):this(name)
        {
            this.age = age;
        }
    }

base

指的是父类对象。在子类中使用base,调用父类的成员

  1. 子类调用父类的构造函数
 class Person//父类
    {
        public int _age;
        public Person(int age)
        {
            this._age = age;
        }       
    } 
    class Chinese : Person//Chines是子类
    {
        public Chinese(int age):base( age)
        {
        }    
    }
  1. 在子类中调用父类的方法与成员
    打印结果为:Foo
    再调用子类方法
class Program
    {
        static void Main(string[] args)
        {
            Person person = new Chinese(1);
            person.Foo();           
            Console.Read();
        }
    }
class Person//父类
    {
        public string name;
        public int _age;
        public Person(int age)
        {
            this._age = age;
        }
        public virtual void Foo()
        {
            Console.WriteLine("Foo");
        }
    }
    class Chinese : Person//Chines是子类
    {
        public override void Foo()
        {
            base.Foo();
            Console.WriteLine("再调用子类方法");
        }

        public Chinese(int age) : base(age)
        {

        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_41707267/article/details/84206254