怎么就没人提到抽象类用于多态呢!??下面通过使用继承的多态(子类中有不同类型的人,年轻人和老年人等)来说明抽象类使用在多态中的好处:
- //PersonStyle类是抽象地,它不表示特定的哪个类型的人,不打算实例化,而是作为不同类型人的祖先类,包含应用到的不同类型的人的信息,存储不同类型的变量在PersonStye类中声明,然后由子孙继承;
- abstract class PersonStyle
- {
-
- /// <summary>
- /// 使用可见修饰符定义类成员,派生类将会继承它
- /// </summary>
- protected string name;
- protected string category;
- public PersonStyle(string Name, string Category)
- {
- name = Name;
- category = Category;
-
-
- }
- /// <summary>
- /// 返回一个字符串包括人员的信息
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- string result = "Name:" + name + "\n";
- result +="Category:"+category+"\n";
- return result;
- }
- /// <summary>
- /// 定义一个抽象方法可以为不同人(年轻人,老年人等)调用
- /// </summary>
- /// <returns></returns>
- public abstract string Re();
- }
复制代码- class PersonMember
- {
- private PersonStyle[] personlist;
- public PersonMember()
- {
-
- //方法触发时引用指向的对象类型用来决定要触发哪个版本的方法
- personlist = new PersonStyle[2];
- personlist[0] = new OldPerson("steven", "老人");
- personlist[1] = new NewPerson("wifi", "少年", "运动");
- }
- public void SayHello()
- {
- string login;
- for (int count = 0; count < personlist.GetLength(0); count++)
- {
- Console.WriteLine(personlist[count]);
- Console.WriteLine();
- login=personlist[count].Re();
- Console.WriteLine(login);
- }
- }
- }
复制代码- class OldPerson:PersonStyle
- {
- public OldPerson(string Name, string Category)
- :base(Name,Category )
- {
-
- }
-
- public override string Re()
- {
- return ("重写抽象方法!\n");
- }
- }
复制代码- class NewPerson:PersonStyle
- {
- private string hobby;
- /// <summary>
- /// base引用触发父类的构造函数 /// </summary>
- /// <param name="Name"></param>
- /// <param name="Category"></param>
- public NewPerson(string Name, string Category,string Hobby)
- :base(Name,Category )
- {
- hobby =Hobby ;
- }
- public override string ToString()
- {
- string result = base.ToString();
- result += "Hobby:" + hobby;
- return result;
- }
- /// <summary>
- /// 通过继承间接引用私有方法! /// </summary>
- /// <returns></returns>
- private string Sleeping()
- {
- return ("\n私有方法间接引用!");
- }
- public override string Re()
- {
- return (Sleeping());
- }
-
- }
复制代码- static void Main(string[] args)
- {
- PersonMember myperson = new PersonMember();
- myperson.SayHello();
-
-
- Console.ReadKey();
- }
复制代码 |