using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace week2._1
// 基类
class Shape
public void setLength(int len)
length = len;
public void setWidth(int wid)
width = wid;
protected int length;
protected int width;
//派生类
class Rectangle : Shape
private int height;
public int getArea()
return length * width;
class Program
static void Main(string[] args)
//创建对象
Rectangle rect = new Rectangle();
rect.setLength(5);
rect.setWidth(6);
Console.WriteLine(rect.getArea());
Console.ReadLine();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace week2._1
class Shape
protected int width;
protected int height;
public void setWidth(int w)
width = w;
public void setHeight(int h)
height = h;
//基类PaintCost
public interface PaintCost
int getCost(int area);
//派生类
class Rectangle: Shape, PaintCost
public int getArea()
return width * height;
public int getCost(int area)
return area * 70;
class test
static void Main(string[] args)
Rectangle r = new Rectangle();
int area;
r.setHeight(7);
r.setWidth(8);
area = r.getArea();
Console.WriteLine(area);
Console.WriteLine(r.getCost(area));
Console.ReadKey();
}
结果:
56
3920
关于继承的几点:
1、继承的语法:class 子类类名 : class 父类类名{ //子类类体 }
2、继承的特点:子类拥有所有父类中所有的字段、属性和方法
3、一个类可以有多个子类,但是父类只能有一个
4、一个类在继承另一个类的同时,还可以被其他类继承
5、在 C# 中,所有的类都直接或者间接的继承自 Object 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace week2._1
class Program
class father
public father()
Console.WriteLine("father");
class son : father
public son()
Console.WriteLine("son");
static void Main(string[] args)
son s = new son();
Console.ReadKey();
}