A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 庞海瑞 中级黑马   /  2013-8-10 12:06  /  990 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

this与base用法是相同的吗?

评分

参与人数 1技术分 +1 收起 理由
赵宗荣 + 1

查看全部评分

4 个回复

倒序浏览
1.保留字this仅限于在构造函数,类的方法和类的实例中使用;
2.base关键字主要是为派生类调用基类成员提供一个简写的方法。
回复 使用道具 举报
base和this用法注意:

base常用于,在派生类对象初始化时和基类进行通信。
base可以访问基类的公有成员和受保护成员,私有成员是不可访问的。
this指代类对象本身,用于访问本类的所有常量、字段、属性和方法成员,而且不管访问元素是任何访问级别。因为,this仅仅局限于对象内部,对象外部是无法看到的,这就是this的基本思想。另外,静态成员不是对象的一部分,因此不能在静态方法中引用this。
在多层继承中,base可以指向的父类的方法有两种情况:一是有重载存在的情况下,base将指向直接继承的父类成员的方法;而没有重载存在的情况下,base可以指向任何上级父类的公有或者受保护方法。

评分

参与人数 1技术分 +2 收起 理由
赵宗荣 + 2

查看全部评分

回复 使用道具 举报
this操作数代表的是指向此对象的参考指针。也就是说,在建立对象的实体后,我们就可以使用this来存取到此对象实体。另外,this操作数也可以用来解决名称相同的问题。 需要注意的是:静态方法中不能使用this。
base是在继承的时候调用父类成员(非私有成员)的时候用。
例如:
string _name;
        protected double s;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        char _gender;

        public char Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }

        public void PersonSay()
        {
            Console.WriteLine("我是Person{0}----{1}---{2}",this.Name,this.Age,this.Gender);
        }

        public Person(string name, int age, char gender)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }
而调用父类构造函数时需使用base
public class Student : Person
    {
        int _id;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public void StudentSay()
        {
            Console.WriteLine("我是学生");
        }

        public Student(string name, int age, char gender, int id)
            : base(name, age, gender)
        {
            this.Id = id;
        }

    }
this还可以调用自己的构造函数

public Person(string name, int age, char gender, double chinese)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
            this.Chinese = chinese;
        }

        //this另一种作用调用自己的构造函数
        public Person(string name, int age, char gender)
            : this(name, age, gender, 0)
        {
            //this.Name = name;
            //this.Age = age;
            //this.Gender = gender;
        }


        public Person(string name, int age, double chinese)
            : this(name, age, '\0', chinese)
        {
            //this.Name = name;
            //this.Age = age;
            //this.Chinese = chinese;
        }
这样可以增强复用性。

评分

参与人数 1技术分 +1 收起 理由
赵宗荣 + 1

查看全部评分

回复 使用道具 举报 1 0
您需要登录后才可以回帖 登录 | 加入黑马