码迷,mamicode.com
首页 > 其他好文 > 详细

this关键字之一个有趣的用法

时间:2015-08-03 18:33:19      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

this关键字

1.首先一个用处就是代表当前类的对象。

2.当我们对构造函数进行重载的时候代码如下:

 public class Class1
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int English { get; set; }
        public int Math { get; set; }
        public int Chinese { get; set; }
        public Class1(string name,int age,string grade,int english,int math,int chinese)
        {
            this.Name = name;
            this.Age = age;
            this.Grade = grade;
            this.English = english;
            this.Math = math;
            this.Chinese = chinese; 
        }
        public Class1(string name,int english, int math, int chinese)
        {
            this.Name = name;
            this.English = english;
            this.Math = math;
            this.Chinese = chinese;
        }
        public Class1(string name, int age)
        {
            this.Name = name;
            this.Age = age;            
        }
        public Class1()
        {
           
        }
    }

 以上代码完全没有问题,但是不免有些代码冗余的现象。我们可以使用this关键字

 public class Class1
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int English { get; set; }
        public int Math { get; set; }
        public int Chinese { get; set; }
        public Class1(string name,int age,string grade,int english,int math,int chinese)
        {
            this.Name = name;
            this.Age = age;
            this.Grade = grade;
            this.English = english;
            this.Math = math;
            this.Chinese = chinese; 
        }
        public Class1(string name,int english, int math, int chinese):this(name,0,"c",english,math,chinese)
        {
            //this.Name = name;
            //this.English = english;
            //this.Math = math;
            //this.Chinese = chinese;
        }
        public Class1(string name, int age)
        {
            this.Name = name;
            this.Age = age;            
        }
        public Class1()
        {
           
        }

       
    }

 即this的第二个用处为在类中显式的调用本类的构造函数

this关键字之一个有趣的用法

标签:

原文地址:http://www.cnblogs.com/hunternet/p/4699909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!