zoukankan      html  css  js  c++  java
  • c#基础-构造函数 this new

    构造函数
    作用:帮助我们初始化对象(给对象的每个属性依次的赋值)
    构造函数是一个特殊的方法:
    1)、构造函数没有返回值,连void也不能写。
    2)、构造函数的名称必须跟类名一样。

    创建对象的时候会执行构造函数
    构造函数是可以有重载的。
    ***

    public Student()
    //类当中会有一个默认的无参数的构造函数,当你写一个新的构造函数之后,不管是有参数的还是
    //无参数的,那个默认的无参数的构造函数都被干掉了。
    {}

               //类名
    1
    public Student(string name, int age, char gender) 2 { 3 this.Name = name; 4 if (age < 0 || age > 100) 5 { 6 age = 0; 7 } 8 this.Age = age; 9 this.Gender = gender; 10 }

    8、new关键字
    Person zsPerson=new Person();
    new帮助我们做了3件事儿:
    1)、在内存中开辟一块空间
    2)、在开辟的空间中创建对象
    3)、调用对象的构造函数进行初始化对象


    9、this关键字
    1)、代表当前类的对象
    2)、在类当中显示的调用本类的构造函数 :this

              类名
    1
    public Student(string name, int age, char gender, int chinese, int math, int english) 2 { 3 this.Name = name; 4 this.Age = age; 5 this.Gender = gender; 6 this.Chinese = chinese; 7 this.Math = math; 8 this.English = english; 9 //构造函数 10 } 11 public Student(string name, int chinese, int math, int english):this(name,0,'c',chinese,math,english) 12 {//构造函数的名称必须跟类名一样。特殊的方法 this的用法 13 //构造函数没有返回值,连void也不能写 14 //在欻昂就对象的时候会调用构造函数 15 //this.Name = name; 16 //this.Chinese = chinese; 17 //this.Math = math; 18 //this.English = english; 19 }
  • 相关阅读:
    9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路(转)
    Path Sum(参考别人,二叉树DFS)
    tcp/ip
    常见Unix指令
    Pascal's Triangle II
    Implement strStr()
    LeetCode总结
    从LLVM源码学C++(一)
    面试题:1到N中,1出现的次数
    面试题:数组划分成两个子数组,和的差值的绝对值最小
  • 原文地址:https://www.cnblogs.com/liuweiqiang11188/p/6676779.html
Copyright © 2011-2022 走看看