1,继承
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace K1
{
public abstract class Shape
{
public abstract int Area(); //获取形状面积
}
/********** Begin *********/
public class Square : Shape
{
int side=0;
public Square(int _side)
{
side=_side;
}
public override int Area( )
{
return side*side;
}
}
/********** End *********/
public class myCaller
{
public static void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
string side = Console.ReadLine();
Square s = new Square(Convert.ToInt32(side));
Console.WriteLine("Square Area:" + s.Area());
}
}
}
}
2,多态
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace K2
{
public abstract class Shape
{
public abstract int Area(); //获取形状面积
}
/********** Begin *********/
//圆形类和正方形类
public class Circular : Shape
{
const int PI =3;
int side=0;
public Circular(int _side)
{
side=_side;
}
public override int Area()
{
return PI*side*side;
}
}
public class Square : Shape
{
int side=0;
public Square(int _side)
{
side=_side;
}
public override int Area()
{
return side*side;
}
}
/********** End *********/
public class myCaller
{
public static void Main(string[] args)
{
Circular c = new Circular(4);
Square s = new Square(4);
Shape shape1 = s;
Shape shape2 = c;
Console.WriteLine("Square Area:" + shape1.Area());
Console.WriteLine("Circular Area:" + shape2.Area());
}
}
}
3,运算符的重载
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace K3
{
public class Community
{
private int number; //人数
public Community(int number)
{
this.number = number;
}
/********** Begin *********/
//重载+运算符
public static int operator + (Community v, Community c)
{
return v.number+c.number;
}
/********** End *********/
}
public class myCaller
{
public static void Main(string[] args)
{
Community violin = new Community(50); //小提琴社
Community cello = new Community(27); //大提琴社
int total = violin + cello;
Console.WriteLine("The number of participants in this event is:" + total);
}
}
}
4,interface接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace K4
{
/********** Begin *********/
//定义接口IColor和IShape
interface IColor
{
void setColor(string color);
}
interface IShape
{
void setShape(string _shape);
}
/********** End *********/
class myBox : IColor, IShape
{
private string color;
private string shape;
public void showBox()
{
Console.WriteLine("box color:" + color);
Console.WriteLine("box shape:" + shape);
}
/********** Begin *********/
//实现接口函数
public void setColor(string color)
{
this.color=color;
}
public void setShape(string _shape)
{
shape=_shape;
}
/********** End *********/
}
public class myCaller
{
public static void Main(string[] args)
{
myBox box = new myBox();
box.setColor("Grey"); //调用实现的接口函数
box.setShape("Cube");
box.showBox();
}
}
}