Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9691

【Unity Learn】見たからまとめる(その2)【中級レベルのスクリプティング】

$
0
0
この記事について タイトル通りの記事 詳細はその1の記事からどうぞ ポリモーフィズム ポリモーフィズムとは 同じ関数であっても呼び出すクラスが異なる場合異なる挙動をすることが出来る多様性の事 実例 親クラスとなるFruitクラスを定義 public class Fruit { public Fruit() { Debug.Log("1st Fruit Constructor Called"); } public void Chop() { Debug.Log("The fruit has been chopped."); } public void SayHello() { Debug.Log("Hello, I am a fruit."); } } Fruitクラスを継承するAppleクラスを定義 public class Apple : Fruit { public Apple() { Debug.Log("1st Apple Constructor Called"); } // Apple には、独自のバージョンの Chop() と SayHello() が存在 // "new"というキーワードは以降のオーバーライドで出てくる public new void Chop() { Debug.Log("The apple has been chopped."); } public new void SayHello() { Debug.Log("Hello, I am an apple."); } } 上記2つのクラスを使用するクラスを定義 public class FruitSalad : MonoBehaviour { void Start () { // ここで、変数 "myFruit" の型は Fruit なのに // Apple クラスのオブジェクトへの参照が割り当てられている // この場合Fruit is A appleでありAppleは親オブジェクトのFruitを継承しているので // Fruitの変数名でAppleクラスのコンストラクタを読んでも問題なく使用できる // アップキャスティングと呼ばれる // この場合myFruitはApple型ではなくFruit型になることに要注意 Fruit myFruit = new Apple(); myFruit.SayHello(); myFruit.Chop(); // ダウンキャスティングとの説明 // Fruit 型の変数 "myFruit" には、実際には Apple への参照が格納されてる // よって、Apple 型の変数に戻すことが可能 // これをダウンキャスティングと呼びこれにより、Apple 型の変数として使用可能となる // この処理を行う前は、Fruit 型の変数としてしか使用できなかったことに注意 Apple myApple = (Apple)myFruit; myApple.SayHello(); myApple.Chop(); } } /*実行結果(本来入っていないが、見やすくするため改行を入れる) Hello, I am a fruit. The fruit has been chopped. Hello, I am an apple. The apple has been chopped. */

Viewing all articles
Browse latest Browse all 9691

Trending Articles