继承
Fruit 类
//这是基类,也称为父类。public class Fruit{public string color;//这是 Fruit 类的第一个构造函数,不会被任何派生类继承。public Fruit(){color = "orange";Debug.Log("1st Fruit Constructor Called");}//这是 Fruit 类的第二个构造函数,不会被任何派生类继承。public Fruit(string newColor){color = newColor;Debug.Log("2nd Fruit Constructor Called");}public void Chop(){Debug.Log("The " + color + " fruit has been chopped.");}public void SayHello(){Debug.Log("Hello, I am a fruit.");}}
Apple 类
//这是派生类,也称为子类。public class Apple : Fruit{//这是 Apple 类的第一个构造函数。它立即调用父构造函数,甚至在它运行之前调用。public Apple(){//注意 Apple 如何访问公共变量 color,该变量是父 Fruit 类的一部分。color = "red";Debug.Log("1st Apple Constructor Called");}//这是 Apple 类的第二个构造函数。它使用“base”关键字指定要调用哪个父构造函数。public Apple(string newColor) : base(newColor){//请注意,该构造函数不会设置 color,因为基构造函数会设置作为参数传递的 color。Debug.Log("2nd Apple Constructor Called");}}
FruitSalad 类
public class FruitSalad : MonoBehaviour{void Start (){//让我们用默认构造函数来说明继承。Debug.Log("Creating the fruit");Fruit myFruit = new Fruit();Debug.Log("Creating the apple");Apple myApple = new Apple();//调用 Fruit 类的方法。myFruit.SayHello();myFruit.Chop();//调用 Apple 类的方法。//注意 Apple 类如何访问Fruit 类的所有公共方法。myApple.SayHello();myApple.Chop();//现在,让我们用读取字符串的//构造函数来说明继承。Debug.Log("Creating the fruit");myFruit = new Fruit("yellow");Debug.Log("Creating the apple");myApple = new Apple("green");//调用 Fruit 类的方法。myFruit.SayHello();myFruit.Chop();//调用 Apple 类的方法。//注意 Apple 类如何访问//Fruit 类的所有公共方法。myApple.SayHello();myApple.Chop();}}
多态
使用多态、向上转换、向下转换在继承的类之间创建强大而动态的功能。
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.");}}
Apple 类
public class Apple : Fruit{public Apple(){Debug.Log("1st Apple Constructor Called");}//Apple 有自己的 Chop() 和 SayHello() 版本。//运行脚本时,请注意何时调用Fruit 版本的这些方法以及何时调用Apple 版本的这些方法。//此示例使用“new”关键字禁止来自 Unity 的警告,同时不覆盖Apple 类中的方法。public new void Chop(){Debug.Log("The apple has been chopped.");}public new void SayHello(){Debug.Log("Hello, I am an apple.");}}
FruitSalad 类
public class FruitSalad : MonoBehaviour{void Start (){//请注意,这里的变量“myFruit”的类型是Fruit,但是被分配了对 Apple 的引用。//这是由于多态而起作用的。由于 Apple 是 Fruit,因此这样是可行的。//虽然 Apple 引用存储在 Fruit 变量中,但只能像 Fruit 一样使用Fruit myFruit = new Apple();myFruit.SayHello();myFruit.Chop();//这称为向下转换。//Fruit 类型的变量“myFruit”实际上包含对 Apple 的引用。//因此,可以安全地将它转换回 Apple 变量。//这使得它可以像 Apple 一样使用,而在以前只能像 Fruit一样使用。Apple myApple = (Apple)myFruit;myApple.SayHello();myApple.Chop();}}
