this关键字的示例

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


namespace ThisKeyWord
{
    public class Student
    {
        public Student (string n,string s,int a,int g)
        {
            name = n;
            sex = s;
            age = a;
            grade = g;
        }
        private string _name;
        public string name
        {
            get {return _name ;}
            set {_name=value;}
        }
        private string _sex;
        public string sex
        {
            get { return _sex; }
            set { _sex = value; }
        }
        private int _age;
        public int age
        {
            get { return _age; }
            set { _age = value; }
        }
        private int _grade;
        public int grade
        {
            get { return _grade; }
            set { _grade = value; }
        }
        //加入社团
        public bool joinCommunity(StudentCommunity community)
        {
            //将类的当前实例加入社团
            return community.addMember(this);
        }
    }
}



namespace ThisKeyWord
{
    public class StudentCommunity
    {
        //社团可以容纳的最多学生数
        private const int MaxStudents = 100;
        private Student[] members = new Student[MaxStudents];
        //社团名字
        private string _name;
        public string name
        {
            get { return _name; }
            set { _name = value; }
        }
        //社团已加入的学生人数
        private int _count = 0;
        public int count
        {
            get { return _count; }
        }
        //加入一个新学生社团
        public bool addMember(Student s)
        {
            if(count <MaxStudents)
            {
                members[count] = s;
                _count++;
                return true;
            }
            else
            {
                return false;
            }
        }
        public void displayMember()
        {
            for(int i=0;i<count;i++)
            {
                Student s = members[i];
                Console.WriteLine("成员[{0}]\t姓名:{1};性别:{2};年龄:{3};年级:{4}", i + 1, s.name, s.sex, s.age, s.grade);
            }
        }
}

namespace ThisKeyWord
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentCommunity community = new StudentCommunity();
            community.name = "编程交流社团";
            Student student = new Student("张三", "男", 21, 2);
            student.joinCommunity(community);
            student=new Student("王丽","女",22,3);
            student.joinCommunity(community);
            community.displayMember();
            Console.ReadLine();
        
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_qwer/article/details/66475929
今日推荐