C# 继承、重载、多态

写个测试,一看便知

 

父类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Component
{
    public virtual void Test()
    {
        UnityEngine.Debug.Log("this is parent component");
    }
}

  

子类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SubComponent : Component
{
    public override void Test()
    {
        UnityEngine.Debug.Log("this is sub component");
    }
}

  

调用结果:

//Component com = new SubComponent();
//com.Test();//print:this is sub component

//Component com = new Component();
//com.Test();//print:this is parent component

//Component com = new SubComponent();
//(com as SubComponent).Test();//print:this is sub component

//Component com = new Component();
//(com as SubComponent).Test();//报错,print:NullReferenceException

  

posted on 2022-12-22 17:50  Jason_c  阅读(20)  评论(0编辑  收藏  举报