C# 第4次实验报告:面向对象编程进阶

C# 所有作业和实验报告:https://blog.csdn.net/COCO56/article/details/102803267

一、实验目的及要求

1.会使用类的继承机制派生子类。
2.会使用虚函数、抽象类、接口实现多态。
3.会使用List和Dictionary泛型集合类组织数据。
4.会使用ArryList和Hashtable非泛型集合类组织数据。
5.掌握委托的定义和使用方法。
6.会使用泛型知识设计程序。
7.会使用C#反射机制获取类信息。

二、实验内容(或实验原理、实验拓扑)

第一次:

  1. 写一个Student类和一个Teacher类,他们都有一个打招呼的方法,不同的是Studetn打招呼是说"大家好,我叫XX,我今年XX岁了,我的爱好是XXX",Teacher的打招呼的方法是说"大家好,我叫XX,我今年XX岁了,我已经工作XX年了"?
  2. 自己定义一个父类Person,两个子类Teacher和Student类.练习类内部构造器的调用,练习子类调用父类的构造器
  3. 自己试试,子类可以自动转父类,父类转子类要通过强转.为了不出错,可以先通过is判断或用as转换

第二次:

  1. 定义一个动物类,在动物类中有一个叫的抽象方法. 写两个子类,一个猫一个狗,继承自动物类,并实现相应的抽象方法.(抽象类)
  2. 在一个程序中,既想实现按年龄排序,又想实现按姓名排序,还要实现按人气值排序,怎么办?

第三次

  1. 创建一个集合,里面添加一些数字,求平均值与和,最大值,最小值,并在控制台显示输出结果。
  2. 写一个长度为10的集合,要求在里面随机地存放10个数字,并在控制台上显示输出这10个数字。(提示:用到Random随机数类中的Next方法,首先创建随机数对象,然后调用Next方法)。
  3. 定义一个集合类(学生类),不仅可以通过下标查找学生,还可以通过姓名查找(设姓名没有重复)

第四次

  1. 将一个字符串数组中每个元素都转换成大写、小写,每个元素两边都加上双引号。

第五次

  1. 一个简单的类,包含一个有参数的构造器,一个GetValue的方法,一个Value属性,运用反射知识通过方法的名称来得到方法并且调用之。

三、实验设备与环境

I7 7700HQ+16G内存+48TB分布式硬盘的笔记本电脑、Windows 10 1903政府版、Visual Studio 2019 企业版、.NET Framework 4.7.2

四、实验设计方案(包括实验步骤、设计思想、算法描述或开发流程等)

Created with Raphaël 2.2.0 Start Write a student class and a teacher class Define a father class person Practice subclass calling the constructor of the parent class try subclass to superclass and superclass to subclass End

五、实验结果(包括设计效果、测试数据、运行结果等)

第一次

  1. 写一个Student类和一个Teacher类,他们都有一个打招呼的方法,不同的是Studetn打招呼是说"大家好,我叫XX,我今年XX岁了,我的爱好是XXX",Teacher的打招呼的方法是说"大家好,我叫XX,我今年XX岁了,我已经工作XX年了"?
  2. 自己定义一个父类Person,两个子类Teacher和Student类.练习类内部构造器的调用,练习子类调用父类的构造器
  3. 自己试试,子类可以自动转父类,父类转子类要通过强转.为了不出错,可以先通过is判断或用as转换
    在这里插入图片描述

第二次

  1. 定义一个动物类,在动物类中有一个叫的抽象方法. 写两个子类,一个猫一个狗,继承自动物类,并实现相应的抽象方法.(抽象类)
    在这里插入图片描述
  2. 在一个程序中,既想实现按年龄排序,又想实现按姓名排序,还要实现按人气值排序,怎么办?
    在这里插入图片描述

第三次

  1. 创建一个集合,里面添加一些数字,求平均值与和,最大值,最小值,并在控制台显示输出结果。
    在这里插入图片描述
  2. 写一个长度为10的集合,要求在里面随机地存放10个数字,并在控制台上显示输出这10个数字。(提示:用到Random随机数类中的Next方法,首先创建随机数对象,然后调用Next方法)。
    在这里插入图片描述
  3. 定义一个集合类(学生类),不仅可以通过下标查找学生,还可以通过姓名查找(设姓名没有重复)
    在这里插入图片描述

第四次

  1. 将一个字符串数组中每个元素都转换成大写、小写,每个元素两边都加上双引号。
    在这里插入图片描述

第五次

  1. 一个简单的类,包含一个有参数的构造器,一个GetValue的方法,一个Value属性,运用反射知识通过方法的名称来得到方法并且调用之。
    在这里插入图片描述

六、实验小结(包括收获、心得体会、注意事项、存在问题及解决办法、建议等)

委托和事件在.NET Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易。

c#委托和事件它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去的人每次见到委托和事件就觉得心里憋得慌,浑身不自在。

委托的概念:委托是用户自定义的类,它定义了方法的类型。储存的是一系列具有相同参数和返回类型方法的地址列表,调用委托时,此委托列表的所有方法都将被执行。

委托类型的定义:委托类型必须在被用来创建变量以及类型对象之前声明。

委托类型的声明:

  1. 以delegate关键字开头。
  2. 返回类型+委托类型名+参数列表

七、附录(包括作品、流程图、源程序及命令清单等)

第一次

  1. 写一个Student类和一个Teacher类,他们都有一个打招呼的方法,不同的是Studetn打招呼是说"大家好,我叫XX,我今年XX岁了,我的爱好是XXX",Teacher的打招呼的方法是说"大家好,我叫XX,我今年XX岁了,我已经工作XX年了"?
  2. 自己定义一个父类Person,两个子类Teacher和Student类.练习类内部构造器的调用,练习子类调用父类的构造器
  3. 自己试试,子类可以自动转父类,父类转子类要通过强转.为了不出错,可以先通过is判断或用as转换
  • Program.cs
    using System;
    
    namespace _1_1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student stu = new Student()
                {
                    Name = "Coco",
                    Age = 22,
                    Hobby = "coding"
                };
                stu.hello();
    
                Teacher t = new Teacher();
                t.Name = "Mr. Smith";
                t.Age = 42;
                t.WorkingAge = 15;
                t.hello();
    
                Console.WriteLine();
                //里氏转换:1)子类可以赋值给父类
                Person p = new Student("Join", 18, "Running");
                //Student ss = (Student)p;  有风险
    
                //2)如果父类中装的是子类对象,那么可以将这个父类转换为子类对象
    
                //3)子类对象可以调用父类中的成员,但是父类对象永远只能调用自己的成员
    
                //is用法:表示类型转换 转换成功返回True,否则False
                //强制类型转换 由大类型转换为小类型 有风险
                if (p is Student)
                {
                    Console.WriteLine("可以转换,正在进行转换");
                    //as用法 表示类型转化 转换成功返回对应的对象 否则返回一个null
                    Student t2 = p as Student;
                    t2.hello();
                }
                else
                {
                    Console.WriteLine("不可以转换");
                }
    
                Console.WriteLine("\nPress any key to quit.");
                Console.ReadKey();
            }
        }
    }
    
  • Person.cs
    using System;
    
    namespace _1_1
    {
        public class Person
        {
            public string Name;
            public double Age;
    
           public Person(string name, double age)
            {
                this.Name = name;
                this.Age = age;
            }
    
            public Person()
            {
                this.Name = "Null";
                this.Age = 0;
            }
            public void hello()
            {
                Console.WriteLine("我是人类");
            }
        }
    }
    
  • Student.cs
    using System;
    
    namespace _1_1
    {
    	class Student: Person
        {
    		public string Hobby;
    
            public Student(): base()
            {
                this.Hobby = "Null";
            }
    
            public Student(string name, double age, string hobby) :
                base(name, age)
            {
                this.Hobby = hobby;
            }
    
            public void hello()
    		{
    			Console.WriteLine("我叫{0},我今年{1}岁了,我的爱好是{2}。", this.Name, this.Age, Hobby);
    		}
    	}
    }
    
  • Teacher.cs
    using System;
    
    namespace _1_1
    {
    	class Teacher : Person
        {
    		public double WorkingAge;
    
            public Teacher() { }
    
            public Teacher(string name, double age, double workingAge) :
                base(name, age)
            {
                this.WorkingAge = workingAge;
            }
    
            public void hello()
    		{
    			Console.WriteLine("我叫{0},我今年{1}岁了,我已经工作{2}年了。", this.Name, this.Age, WorkingAge);
    		}
    	}
    }
    

第二次:

  1. 定义一个动物类,在动物类中有一个叫的抽象方法. 写两个子类,一个猫一个狗,继承自动物类,并实现相应的抽象方法.(抽象类)
    Program.cs

    using System;
    //定义一个动物类,在动物类中有一个叫的抽象方法.  写两个子类,一个猫一个狗,继承自动物类,并实现相应的抽象方法.(抽象类)
    
    namespace _2
    {
        abstract class Animal
        {
            public abstract void cry();
        }
    
        class Cat : Animal
        {
            public override void cry()
            {
                Console.WriteLine("喵喵!");
            }
        }
    
        class Dog : Animal
        {
            public override void cry()
            {
                Console.WriteLine("汪汪!");
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Cat cat = new Cat();
                Dog dog = new Dog();
                cat.cry();
                dog.cry();
                Console.ReadLine();
            }
        }
    }
    
  2. 在一个程序中,既想实现按年龄排序,又想实现按姓名排序,还要实现按人气值排序,怎么办?
    Program.cs

    using System;
    using System.Collections.Generic;
    
    namespace _2_2
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Teacher> list = new List<Teacher>();
                list.Add(new Teacher(1, "张三", 10000,100));
                list.Add(new Teacher(2, "张三", 10000, 101));
                list.Add(new Teacher(3, "宋江", 10000,101));
                list.Add(new Teacher(4, "李四", 5000,102));
                list.Add(new Teacher(5, "王五", 1000,103));
                foreach (Teacher t in list)
                    Console.WriteLine(t);
    
                Console.WriteLine("排序后:");
                list.Sort();//IComparable
                foreach (Teacher t in list)
                    Console.WriteLine(t);
    
                Console.ReadKey();
            }
        }
        public class Teacher : IComparable<Teacher>
        {
            public int Id;
            public string Name;
            public decimal Salary;
            public int PopularityValues;
    
            public Teacher(int id, string name, decimal salary, int popularityValues)
            {
                this.Name = name;
                this.Id = id;
                this.Salary = salary;
                this.PopularityValues = popularityValues;
            }
            public override string ToString()
            {
                return "id:" + this.Id + "\tname:" + this.Name + "\tsalary:" + this.Salary + "\tpopularityValues:"+this.PopularityValues;
            }
            public int CompareTo(Teacher other)
            {
                if (this.Salary == other.Salary)
                {
                    if (this.Name == other.Name)
                        return (int)(this.PopularityValues - other.PopularityValues);
                    return this.Name.CompareTo(other.Name);
                }
                return (int)(this.Salary - other.Salary);
            }
        }
    }
    

第三次

  1. 创建一个集合,里面添加一些数字,求平均值与和,最大值,最小值,并在控制台显示输出结果。
    Program.cs
    using System;
    using System.Collections;
    
    //1. 创建一个集合,里面添加一些数字,求平均值与和,最大值,最小值,并在控制台显示输出结果。
    
    namespace _3
    {
        class Program
        {
            static void Main(string[] args)
            {
    			//创建一个集合
    			ArrayList list = new ArrayList();
    			//向集合添加一些数字
    			list.AddRange(new int[] { 1, 8, 7, 4, 5, 6, 3, 2, 9 });
    			//新建sum变量来存储和
    			int sum = 0;
    			//新建一个max来存储最大值
    			int max = (int)list[0];
    			//新建一个min来存储最小值
    			int min = (int)list[1];
    
    			//通过一个循环来赋值
    			for (int i = 0; i < list.Count; i++)
    			{
    				//list[i]是object类型,通过里氏转换法强转成int类型
    				if ((int)list[i] > max)
    				{
    					max = (int)list[i];
    				}
    				if ((int)list[i] < min)
    				{
    					min = (int)list[i];
    				}
    				sum += (int)list[i];
    			}
    			//分别输出max,min,sum和avg
    			Console.WriteLine("max="+max);
    			Console.WriteLine("min=" + min);
    			Console.WriteLine("sum=" + sum);
    			Console.WriteLine("avg=" + sum / list.Count);
    			Console.ReadKey();
    		}
        }
    }
    
  2. 写一个长度为10的集合,要求在里面随机地存放10个数字,并在控制台上显示输出这10个数字。(提示:用到Random随机数类中的Next方法,首先创建随机数对象,然后调用Next方法)。
    Program.cs
    using System;
    using System.Collections;
    
    //2. 写一个长度为10的集合,要求在里面随机地存放10个数字,并在控制台上显示输出这10个数字。(提示:用到Random随机数类中的Next方法,首先创建随机数对象,然后调用Next方法)。 
    
    namespace _3_2
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			Random r = new Random();
    			int cnt = 0;
    			ArrayList al = new ArrayList();
    			while (cnt<10)
    			{
    				cnt += 1;
    				al.Add(r.Next());
    			}
    			foreach (var i in al)
    			{
    				Console.WriteLine(i);
    			}
    			Console.ReadKey();
    		}
    	}
    }
    
  3. 定义一个集合类(学生类),不仅可以通过下标查找学生,还可以通过姓名查找(设姓名没有重复)
    MyList.cs
    using System;
    
    namespace _3_3
    {
    	class MyList
    	{
    		private Student[] array;
    		private int count;
    
    		public MyList(int size)
    		{
    			if (size >= 0)
    			{
    				array = new Student[size];
    			}
    		}
    
    		public MyList()
    		{
    			array = new Student[0];
    		}
    
    		//Capacity属性获取容量大小
    		public int Capacity
    		{
    			get { return array.Length; }
    		}
    
    		//Count属性访问元素个数
    		public int Count
    		{
    			get { return count; }
    		}
    
    		//Add()方法添加元素
    		public void Add(Student item)
    		{
    			if (Count == Capacity)
    			{
    				if (Capacity == 0)
    				{
    					array = new Student[4];
    				}
    				else
    				{
    					var newArray = new Student[Capacity * 2];
    					Array.Copy(array, newArray, Count);
    					array = newArray;
    				}
    			}
    			array[Count] = item;
    			count++;
    		}
    
    		//索引器(通过一个Index查找数组中的某个元素)
    		public Student GetItem(int Index)
    		{
    			if (Index >= 0 && Index < Count)
    			{
    				return array[Index];
    			}
    			else
    			{
    				throw new Exception("索引超出范围");
    			}
    		}
    
    		//[index] 访问元素
    		public Student this[int index]
    		{
    			get
    			{
    				return GetItem(index);
    			}
    			set
    			{
    				if (index >= 0 && index < Count)
    				{
    					array[index] = value;
    				}
    				else
    				{
    					throw new Exception("索引超出范围");
    				}
    			}
    		}
    
    		public Student this[string name]
    		{
    			get
    			{
    				int index = IndexOf(name);
    				return GetItem(index);
    			}
    			set
    			{
    				int index = IndexOf(name);
    				if (index >= 0 && index < Count)
    				{
    					array[index] = value;
    				}
    				else
    				{
    					throw new Exception("索引超出范围");
    				}
    			}
    		}
    
    		//Insert()插入元素
    		public void Insert(int index, Student item)
    		{
    			if (Count == Capacity)
    			{
    				if (Capacity == 0)
    				{
    					array = new Student[4];
    				}
    				else
    				{
    					var newArray = new Student[Capacity * 2];
    					Array.Copy(array, newArray, Count);
    					array = newArray;
    				}
    			}
    			for (int j = count - 1; j >= index; j--)
    			{
    				array[j + 1] = array[j];
    			}
    			array[index] = item;
    			count++;
    		}
    
    		//IndexOf()方法取得一个元素所在列表中的索引位置(从前往后搜索)
    		public int IndexOf(Student item)
    		{
    			for (int i = 0; i < count; i++)
    			{
    				if(array[i].Equals(item))
    				{
    					return i;
    				}
    			}
    			return -1;
    		}
    
    		public int IndexOf(string name)
    		{
    			for (int i = 0; i < count; i++)
    			{
    				if (array[i].Name == name)
    				{
    					return i;
    				}
    			}
    			return -1;
    		}
    
    		//从后往前搜索,搜到满足条件就停止没有找到返回-1
    		public int LastIndexOf(Student item)
    		{
    			for (int i = count - 1; i >= 0; i--)
    			{
    				if (array[i].Equals(item))
    				{
    					return i;
    				}
    			}
    			return -1;
    		}
    
    		//对列表中的元素进行从小到大的排序
    		public void Sort()
    		{
    			for (int j = 0; j < count - 1; j++)
    			{
    				for (int i = 0; i < count - 1 - j; i++)
    				{
    					if (array[i].CompareTo(array[i + 1]) > 0)
    					{
    						Student temp = array[i];
    						array[i] = array[i + 1];
    						array[i + 1] = temp;
    					}
    				}
    			}
    		}
    	}
    }
    
    Person.cs
    using System;
    
    namespace _3_3
    {
        class Person
        {
            public string Name;
    		public int ID;
    		public static int IDCnt = 1;
    
    
    		public Person(string name)
            {
    			this.ID = IDCnt;
    			IDCnt += 1;
                this.Name = name;
            }
    
            public void hello()
            {
                Console.WriteLine("我是人类");
            }
        }
    }
    
    Program.cs
    using System;
    
    //3. 定义一个集合类(学生类),不仅可以通过下标查找学生,还可以通过姓名查找(设姓名没有重复)
    
    namespace _3_3
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			Student stu = new Student("Coco", 99);
    
    			Student stu2 = new Student("Jone", 90);
    
    			MyList myList = new MyList();
    			myList.Add(stu);
    			myList.Add(stu2);
    			Console.WriteLine("通过下标查找学生:");
    			for (int i = 0; i < myList.Count; i++)
    			{
    				myList[i].hello();
    			}
    
    			Console.WriteLine("\n\n通过姓名查找学生:");
    			myList["Jone"].hello();
    			myList["Coco"].hello();
    
    			Console.ReadKey();
    		}
    	}
    }
    
    Student.cs
    using System;
    
    namespace _3_3
    {
        class Student : Person
        {
            public float Score;
    
            public Student(string name, float score) :
                base(name)
            {
                this.Score = score;
            }
    
            public new void hello()
            {
                Console.WriteLine("我的学号是{0},我叫{1},我的分数是{2}。", ID, Name, Score);
            }
    
    		public float CompareTo(Student other)
    		{
    			return (Score - other.Score);
    		}
    	}
    }
    

第四次

  1. 将一个字符串数组中每个元素都转换成大写、小写,每个元素两边都加上双引号。
    Program.cs
    using System;
    
    //将一个字符串数组中每个元素都转换成大写、小写,每个元素两边都加上双引号。
    namespace _4
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			string str = "aBc";
    			Console.WriteLine(str);
    
    			Console.WriteLine("\n全转成大写的:");
    			string u = str.ToUpper();
    			Console.WriteLine(u);
    
    			Console.WriteLine("\n全转成小写的:");
    			string l = str.ToLower();
    			Console.WriteLine(l);
    
    			Console.WriteLine("\n添加引号:");
    			string q = "\""+str +"\"";
    			Console.WriteLine(q);
    
    			Console.ReadKey();
    		}
    	}
    }
    

第五次

  1. 一个简单的类,包含一个有参数的构造器,一个GetValue的方法,一个Value属性,运用反射知识通过方法的名称来得到方法并且调用之。
    Program.cs
    using System;
    using System.Reflection;
    
    //一个简单的类,包含一个有参数的构造器,一个GetValue的方法,一个Value属性,运用反射知识通过方法的名称来得到方法并且调用之。
    namespace _5
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			Type t = typeof(SimpleClass);
    			object o = Activator.CreateInstance(t, "test");
    			MethodInfo mi = t.GetMethod("getValue");
    			mi.Invoke(o, null);
    
    			Console.ReadKey();
    		}
    
    		public class SimpleClass
    		{
    			public string Value;
    
    			public SimpleClass(string v)
    			{
    				Value = v;
    				Console.WriteLine("正在初始化对象,已为Value成功赋值。");
    			}
    			public void getValue()
    			{
    				Console.WriteLine("Value=" + Value);
    			}
    		}
    	}
    }
    
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

COCO56(徐可可)

建议微信红包:xucoco56

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值