this. :可以获取当前类的属性和方法
base.:只能获取父类(被继承)里的属性和方法
public class console : MonoBehaviour {
// Use this for initialization
void Start () {
Triangle triangle = new Triangle();
triangle.name = "三角";
triangle.length = 2;
triangle.width = 3;
// triangle.color = "red";//如果父类的变量权限为private,那么在其他class里无法访问
triangle.showInfo();//运行父类的封装方法
triangle.calcArea();
Debug.Log("三角的面积" + triangle.area);
Square square = new Square();
square.name = "正方形";
square.length = 2;
square.width = 3;
square.showInfo();
square.calcArea();
Debug.Log("正方形的面积"+square.area);
}
// Update is called once per frame
void Update () {
}
public enum POLYGON //设置枚举(下拉栏)
{
triangle,
square,
}
public class Polygon //创建一个Polygon父类
{
public int length;
public int width;
private string color;
public string name;
public float area;
public POLYGON emPolgon;
public void showInfo() //在父类里写方法 函数,在子类调用,这个叫做 [封装]
{
Debug.LogFormat("{0},长:{1},宽:{2}",name,length,width);
}
public virtual void calcArea() //计算面积封装,virtual代表虚函数,可以被子类同名覆盖
{
if (emPolgon == POLYGON.square)
{
area = width * length;
}
else if (emPolgon == POLYGON.triangle)
{
area = width * length/2;
}
}
}
/// <summary>
/// 三角形
/// </summary>
public class Triangle : Polygon//创建一个Triangle子类,继承于Polygon
{
public Triangle()
{
string aaa = name; // 父类public,protected变量都可以在子类的方法 函数里使用
//string bbb = color; // 父类private变量无法在子类的方法 函数里使用
}
public override void calcArea() //计算面积封装,override可以覆盖父类的virtual虚方法
{
area = length * width / 2;
}
}
/// <summary>
/// 正方形
/// </summary>
public class Square : Polygon//创建一个Triangle子类,继承于Polygon
{
public Square()
{
}
public override void calcArea() //计算面积封装,override可以覆盖父类的virtual虚方法
{
area = length * width;
}
}
}