18.this关键字

this关键字的用法

1.指代当前类的实例
2.在类中显式的调用本类中的构造方法。

调用类中构造方法语法 :this

例如:在下例代码中通过在构造方法“)”后加上“:this(参数列表)”来调用相应的构造方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo {


    class Program {

        //字段
        private string _name;
        private int _age;

        //构造方法
        public Program() {
            Console.WriteLine("无参构造执行");
        }

        public Program(string name) :this(){
            this.Name = name;
            Console.WriteLine("参数为name的构造执行");
        }

        public Program(string name,int age):this(name) {
            this.Age = age;
            Console.WriteLine("全参数的构造执行");
        }


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

        public int Age {
            get;
            set;
        }
    }

    class Test {
        static void Main(string[] args) {
            Program p = new Program("张三",20);

            Console.WriteLine("====================================");
            Console.WriteLine("Name为"+p.Name+",Age为"+p.Age);

            Console.ReadKey();
        }
    }
}

运行结果:

通过执行结果分析,可以发现,对于构造函数括号后加了:this(参数列表)的,那么会首先调用this所对应的构造方法。如上例中的全参构造会先调用一个参数的构造,一个参数的构造又会调用无参的构造。所以执行结果会是,无参->一个参->全参。

猜你喜欢

转载自www.cnblogs.com/lz32158/p/12902939.html
今日推荐