构造函数

 1 namespace CSharpDemo
 2 {
 3     class Student
 4     {
 5         //private是私有的,只在类的内部可见
 6         private string stuName;
 7         //默认就是私有的,这下面两个成员
 8         string stuSex;
 9         int stuAge;
10 
11 
12         //一个类如果程序员不写构造函数会提供一个无参的默认的构造函数,如果程序员写了自已的构造函数,那么这个默认的无参的构造函数就收回了
13         //构造函数的特点是,没有返回类型,方法名和类名相同。
14         public Student(string name, string sex, int age)
15         {
16             if (name != "2B")
17             {
18                 //this代表本类对象,也就是谁new就是谁
19                 this.stuName = name;
20             }
21             else
22             {
23                 stuName = "好学生";
24             }
25 
26             if (sex == "" || sex == "")
27             {
28                 this.stuSex = sex;
29             }
30             else
31             {
32                 sex = "";
33             }
34 
35             if (age >= 10 && age <= 50)
36             {
37                 stuAge = age;
38             }
39             else
40             {
41                 stuAge = 18;
42             }
43         }
44 
45         public void SayStudentSelf()
46         {
47             Console.WriteLine("我叫{0} 今年{1}岁了 我是{2}生", this.stuName, stuAge, this.stuSex);
48         }
49     }
50 }

 

posted @ 2018-11-08 15:34  冬夜的火  阅读(153)  评论(0)    收藏  举报