夜光序言:
若是把话说得过于透彻,反而失去了效果,因为人需要被一种神秘的力量左右。
正文:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 夜光测试1
{
//序言:动态多态又称为虚方法
//首先,我们创建一个游戏单位
class GameUnit{ //游戏单位
//1.我们定义一个攻击方法
// virtual表示让Attack方法行为多态
public virtual void Attack()
{
Console.WriteLine("攻击");
}
}
//派生类需要加上override
class AirUnit : GameUnit //夜光:定义为空中单位
{
public override void Attack()
{
Console.WriteLine("空中单位进行攻击");
}
}
//派生类需要加上override
class GroundUnit : GameUnit //夜光:定义为地面单位
{
public override void Attack()
{
Console.WriteLine("地面单位进行攻击");
}
}
class Program
{
static void Main(string[] args)
{
#region 动态多态
//先new两个对象出来
AirUnit au = new AirUnit();
GroundUnit gu = new GroundUnit();
/*au.Attack();
gu.Attack();*/
//1.夜光:没有实线多态的情况
//虽难gameU指向一个AirUnit,但是C#只能识别到au的基类部分
//2.夜光:实现多态后的情况
//识别出gameU就是指向的au(AirUnit),并且C#识别到attack是一个虚方法
//于是调用gameU实际指向对象(au)的类型(AirUnit)的重写版本
/*GameUnit gameU = au;
* 之后我们就可以用GameUnit对游戏对象进行统一的管理
au.Attack();*/
/* GameUnit gameU = au;
gameU.Attack(); //识别出gameU就是指向的au*/
#region Array 版本的对象管理: 夜光精华
/* GameUnit[] guArray = new GameUnit[2]; //我先用数组演示一下
guArray[0] = au;
guArray[1] = gu;
for(int i=0;i< guArray.Length; i++)
{
*//* Console.WriteLine(guArray[i]);//不是这样写,我们是要调用方法*//*
guArray[i].Attack();
}*/
#endregion
#region List 版本的对象管理: 夜光精华
List<GameUnit> guArray = new List<GameUnit>(); //我先用数组演示一下
guArray.Add(au);
guArray.Add(gu);
for (int i = 0; i < guArray.Count; i++)
{
/* Console.WriteLine(guArray[i]);//不是这样写,我们是要调用方法*/
guArray[i].Attack();
}
#endregion
#endregion
Console.ReadLine();
}
}
}
下面我带大家做几个例子,讲解一下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 画图程序
{
class shape
{
/// <summary>
/// 绘制
/// </summary>
public virtual void Draw() //virtual表示这是一个虚方法
{
}
}
class circle : shape
{
public override void Draw() //我们需要重写的只是这个draw方法
{
Console.WriteLine("●"); //拼音输入yq,就会出现形状
}
}
class Rect : shape //这里我们再画个矩形
{
public override void Draw()
{
Console.WriteLine("■"); //拼音输入fk,就会出现形状
}
}
//输出一下三角形
class Triangle : shape
{
public override void Draw()
{
Console.WriteLine("▲"); //夜光
}
}
class Program
{
static void Main(string[] args)
{
#region shape 夜光
//接下来,我们就需要统一的调用一些方法
List<shape> ls = new List<shape>(); //List集合,我们把shape放进去
ls.Add(new circle());
ls.Add(new Rect());
ls.Add(new Triangle());
//我们写一个for循环,来测试一下
for(int i = 0; i < ls.Count; i++)
{
ls[i].Draw(); //ls里面有一个虚方法,我们称为draw
//上面这个就类似于:
//shape s = ls[i];
//s.draw();
}
#endregion
Console.ReadLine();
}
}
}