黑马程序员 构造方法

来源:互联网 发布:在线充值系统网站源码 编辑:程序博客网 时间:2024/06/05 20:53

 

---------------------- Windows Phone 7手机开发.Net培训、期待与您交流! ----------------------

创建对象时,要对类中的很多字段赋值,还有某些字段不允许修改,有些字段要强制性的不能为空。
这些东西都可以通过构造方法来实现,构造方法是一个特殊的方法,它的名字和类的名字相同,并且没有返回值。和方法一样,构造方法同样也能重载。
下面的代码是创建一个类,并且使用了构造方法和构造方法的重载
namespace 类的练习
{
class Student
    {
        string name;
        string gender;
        int age;
        int lscore, mscore, escore;
        public Student(string name,string gender,int age, int lscore,int mscore,int escore)
        {
            this.name = name;
            this.gender = gender;
            this.age = age;
            this.lscore = lscore;
            this.mscore = mscore;
            this.escore = escore;
        }
        public Student(string name, string gender)
        {
            this.name = name;
            this.gender = gender;
            this.age = 0;
            this.lscore = 0;
            this.mscore = 0;
            this.escore = 0;
        }
         public int Escore
        {
            get { return escore; }
        }
        public int Mscore
        {
            get { return mscore; }
        }
        public int Lscore
        {
            get { return lscore; }
        }
        public int Age
        {
            get { return age; }
        }
        public string Name
        {
            get { return name; }
        }
        public string Gender
        {
            get { return gender; }
        }
        public void SayHello()
        {
            Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}同学", name, age, name);
        }
        public void ShowScore()
        {
            int sum = lscore + mscore + escore;
            int avg = sum / 3;
            Console.WriteLine("我叫{0},我的总成绩是{1},我的平均成绩是{2}", name, sum, avg);
        }
    }
}
下面的代码是声明一个对象,并且调用了SayHello和ShowScore方法
namespace 类的练习
{
class Program
    {
        static void Main(string[] args)
        {
            #region 实列化张三
Student zstudent = new Student("张三", "男", 18, 95, 85, 90);
            zstudent.SayHello();
            zstudent.ShowScore();
            #endregion
            #region 实列化小兰
Student xltudent = new Student("小七","女");
xltudent.SayHello();
            xltudent.ShowScore();
            #endregion
            Console.ReadKey();
        }
    }
---------------------- Windows Phone 7手机开发.Net培训、期待与您交流! ---------------------- 详细请查看:http://net.itheima.com/

 

原创粉丝点击