本帖最后由 da11 于 2021-1-27 23:08 编辑
//主Main:
namespace test5_继承_static_结构体
{
class Program
{
//本项目讲解继承、static(静态修饰符)、结构体
static void Main1(string[] args)
{
Stu Stu01 = new Stu();
//Stu类是JiChengClass类的子类,是没有name属性的,name属性在JiChengClass类中
//继承的现象是:
//子类可以使用父类成员
Stu01.name = "testStu01";
Stu01.age=13;
//父类只能使用父类成员
JiChengClass test = new JiChengClass();
test.name="jicheng test";
//子类也可以使用自己的子类成员
Stu01.stuLevel = "A";
//父类型的引用指向子类的对象,只能使用父类成员
JiChengClass test01 = new Stu();
test01.name = "111";
//如果强制使用子类成员,则必须将对象强制转换为Stu类型
Stu test02 = (Stu)test01;
test02.stuLevel = "A";
//以下这句语句会报异常,子类成员和子类成员不能显示转换
//Teacher test03 = (Teacher)test01;
//以下这句语句,如果转换失败,不会抛出异常,但是test03这个对象会为null
Teacher test03 = test01 as Teacher;
//在为null的情况下,赋值是会报“NullReferenceException(未将对象引用设置到对象的实例)”
//等于是null.teacherLevel = "A";
//这个异常在unity报的是英文
//所以需要使用加if判断是否为null才继续执行赋值操作。
if (test03!=null)
{
test03.teacherLevel = "A";
}
Console.WriteLine(Stu01.name +" "+ Stu01.age);
Console.ReadLine();
}
}
} |