继承基础
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cSharpTest
{
class Fxx
{
static void Main(string[] args)
{
}
}
public class Student
{
public Student(string name, int age)
{
this.Name = name;
this.Age = age;
}
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private static int _id;
//静态只能调用静态!
public static void SayId()
{
Console.WriteLine(_id);
}
public void SayHello()
{
Console.WriteLine("My name is {0}, my age is {1}", this.Name, this.Age);
}
}
public class Pupil:Student
{
//必须这么写 不然报错!
public Pupil(string name, int age, int id): base(name, age)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
this.Id = id;
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
public void SayPupil()
{
Console.WriteLine("I am a pupil.");
}
}
}
里氏转换
1.子类可以复制给父类,如果有一个地方需要父类作为参数,可以给父类赋值给父类
Person p1= new Student();
2.如果父类中装的是子类对象,那么可以将父类强转为子类对象
Student s1 =(Student)p1;
3.转换之前需要判断
is 转换成功ture,失败false
as 能转换则返回对应对象,否则返回None
if(p is Teacher)
{
}
else{
}
as用法
Teacher t = p as Teacher();
练习
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsharpTest0621
{
class Fxx
{
static void Main(string[] args)
{
//创建10个对象,循环调用他们的方法
//Student s = new Student();太麻烦
Person[] personList = new Person[10];
Random r = new Random();//随机数对象
for (int i = 0; i < personList.Length; i++)
{
int rNumber = r.Next(1, 6);
switch (rNumber)
{
case 1: personList[i] = new Student();
break;
case 2: personList[i] = new Teacher();
break;
case 3:
personList[i] = new Worker();
break;
case 4:
personList[i] = new Piger();
break;
case 5:
personList[i] = new Gay();
break;
}
}
for (int i = 0; i < personList.Length; i++)
{
if (personList[i] is Student)
{
((Student)personList[i]).StudenSay();
}
else if (personList[i] is Teacher)
{
((Teacher)personList[i]).TeacherSay();
}
else if (personList[i] is Worker)
{
((Worker)personList[i]).WorkerSay();
}
}
}
public class Person
{
public void PersonSay()
{
Console.WriteLine("I am a person.");
}
}
public class Student:Person
{
public void StudenSay()
{
Console.WriteLine("I am a student.");
}
}
public class Teacher:Person
{
public void TeacherSay()
{
Console.WriteLine("I am a teacher.");
}
}
public class Worker : Person
{
public void WorkerSay()
{
Console.WriteLine("I am a Worker.");
}
}
public class Piger : Person
{
public void PigerSay()
{
Console.WriteLine("I am a Piger.");
}
}
public class Gay : Person
{
public void GaySay()
{
Console.WriteLine("I am a Gay.");
}
}
}
}
protected
protected 可以让当前类的内部 已经该类的子类里面
网友评论