close

多型分為靜態與動態兩類

Polymorphism - Static or Compile Time

(1)方法多載 (Method Overloading)

(2)運算子多載 (Operator Overloading)

(Complie Time 是我們在編譯時確定的)

public class GameController : MonoBehaviour
{
    void Start()
    {
        A a = new A ();
        a.Add (1, 2);
        a.Add (0.5f, 0.3f);
    }
}

public class A 
{
    public int Add(int i, int j)
    {
        return i + j;
    }

    public float Add(float i, float j)
    {
        return i + j;
    }
}

其實我們一般在做的運算(+-等等)已經是多載的表現了

為了讓大家更清楚再做一個運算的範例

public class GameController : MonoBehaviour
{
    void Start()
    {
        A a = new A (10, 20);
        A b = new A (5, 8);
        A c = a + b;
    }
}

public class A 
{
    public int hp;
    public int sp;
    public A(int hp, int sp)
    {
        this.hp = hp;
        this.sp = sp;
    }
    static public A operator +(A i, A j)
    {
        return  new A (i.hp + j.hp, i.sp + j.sp);
    }
}

 

Polymorphism Dynamic or Runtime

(1)Virtual / Overriding Method

(Runtime 則是執行調用方法時所檢查的)

public class GameController  : MonoBehaviour
{
    void Start()
    {
        Warrior w = new Warrior ();
        w.Skill ();
        Archer a = new Archer ();
        a.Skill ();
        Mage m = new Mage ();
        m.Skill ();
    }
}

public class RoleBase
{
    public virtual void Skill()
    {
        Debug.Log ("無技能");
    }    
}

public class Warrior : RoleBase
{
    public override void Skill ()
    {
        Debug.Log ("斬殺");
    }
}

public class Archer : RoleBase
{
    public override void Skill ()
    {
        Debug.Log ("瞄準射擊");
    }
}

public class Mage : RoleBase
{
    public override void Skill ()
    {
        Debug.Log ("暴風雪");
    }
}

雖然都是由同一個基底衍生出來的

但是我們可以用方法覆寫來改變方法的功能

但我們如果沒有覆寫 則會繼續使用基底方法

當然我們也可以覆寫再複寫

public class Warrior : RoleBase
{
    public override void Skill ()
    {
        Debug.Log ("斬殺");
    }
}

public class DefWarrior : Warrior
{
    public override void Skill ()
    {
        Debug.Log ("盾牆");
    } 
}

我們也可以防止別人來覆寫

public class Warrior : RoleBase
{
    public sealed override void Skill ()
    {
        Debug.Log ("斬殺");
    }
}

public class DefWarrior : Warrior
{
    public override void Skill () // 錯誤
    {
        Debug.Log ("盾牆");
    } 
}

 

 

歡迎參觀我的FB粉絲

近期會陸續將遊戲上架

請幫忙按讚訂閱唷!

https://www.facebook.com/weight.tw/

arrow
arrow

    Weight 發表在 痞客邦 留言(0) 人氣()