一:
using System;
using System.Collections.Generic;
namespace 虚拟方法的理解0
{
public class shape
{
public int Normal(){return 0; }
public int x{get;private set; }//属性
public int y { get; private set; }
public int Height { get; set; }
public int width { get; set; }
public virtual void RenderShape()
{
Console.WriteLine("渲染");
// return;
}
}
public class Rect:shape//这里对比抽象方法和虚拟方法,抽象不实现会报错,虚拟则不会
{
public override void RenderShape()
{
Console.WriteLine("画一个矩形");
// base.RenderShape();
}
}
public class Circle:shape
{
public override void RenderShape()
{
Console.WriteLine("画一个圆");
// base.RenderShape();
}
}
class Program
{
static void Main(string[] args)
{
//可变类型
var shapes = new List<shape>
{
new Rect(),
new Circle(),
};
foreach (shape item in shapes)//或者var item
{
item.RenderShape();
}
//Console.WriteLine("Hello World!");
}
}
}
二:
using System;
namespace 第二周_虚拟方法的理解
{
public class shape
{
protected int width, length;
public shape(int a = 0, int b = 0)
{
width = a;
length = b;
}
// public virtual int GetArea();//一定要实现
public virtual int GetArea()
{
Console.WriteLine("父类面积的计算:");
return 0;
}
}
public class Rect : shape
{
public Rect(int a = 0, int b = 0) : base(a, b)//后面的a,b其实是Rec里面的a,b
{
//传值过程,从Rect传a,b然后传到base类,调用
//基类shape的构造函数,base指shape
}
public override int GetArea()
{
Console.WriteLine("矩形的面积");
return (width * length);
}
}
public class Triangle:shape
{
public Triangle(int a=0,int b=0):base(a,b)
{
}
public override int GetArea()
{
Console.WriteLine("三角形的面积:");
return width*length/2 ;
}
}
public class AreaCalculator
{
public void CalculateArea(shape sh)//这里虽然写的是shape,但其实以shape为父类的类都可以写入,用大范围包含小范围理解
{
int a;
a = sh.GetArea();
Console.WriteLine("面积:" + a);
}
}
class Program
{
static void Main(string[] args)
{
// Console.WriteLine("Hello World!");
AreaCalculator areaCaculateArea = new AreaCalculator();
Rect rect = new Rect(1,2);
Triangle tr = new Triangle(3,4);
areaCaculateArea.CalculateArea(rect);
areaCaculateArea.CalculateArea(tr);
}
}
}
原文:https://www.cnblogs.com/Nicela/p/13130054.html