构造对象
子类可以构造父类对象
不同于C++的写法,如下:
//基类名 对象实例 = new 派生类名;Fruit myFruit = new Apple();
也可以用父类可以构造子类对象
//派生类名 对象实例 = (派生类名)基类对象名;Apple myApple = (Apple)myFruit;
例如有:
class baseclass{public baseclass() { Console.WriteLine("baseclass"); }public void test() { Console.WriteLine("basemethod"); }}class chirclass:baseclass{public chirclass() { Console.WriteLine("chirclass"); }public void test() { Console.WriteLine("chirmethid"); }}static void Main(string[] args){//用子类构造父类对象baseclass c = new chirclass();c.test();Console.WriteLine("-------------------------");//父类可以构造子类对象,不能这么写//chirclass c2 = new baseclass();baseclass c2 = (chirclass)c;}}
多个类复杂一点:
using UnityEngine;using System.Collections;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.");}}
using UnityEngine;using System.Collections;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.");}}
using UnityEngine;using System.Collections;public class FruitSalad : MonoBehaviour{void Start (){//请注意,这里的变量“myFruit”的类型是//Fruit,但是被分配了对 Apple 的引用。这是//由于多态而起作用的。由于 Apple 是 Fruitd的子类,//因此这样是可行的。虽然 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();}}
动态多态性
C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。
请注意,下面是有关抽象类的一些规则:
- 您不能创建一个抽象类的实例。
- 您不能在一个抽象类外部声明一个抽象方法。
通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为 sealed 时,它不能被继承。抽象类不能被声明为 sealed。
using System;namespace PolymorphismApplication{abstract class Shape{abstract public int area();}class Rectangle: Shape{private int length;private int width;public Rectangle( int a=0, int b=0){length = a;width = b;}public override int area (){Console.WriteLine("Rectangle 类的面积:");return (width * length);}}class RectangleTester{static void Main(string[] args){Rectangle r = new Rectangle(10, 7);double a = r.area();Console.WriteLine("面积: {0}",a);Console.ReadKey();}}}
