动态多态性
C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。
请注意,下面是有关抽象类的一些规则:
您不能创建一个抽象类的实例。您不能在一个抽象类外部声明一个抽象方法。通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为
sealed 时,它不能被继承。抽象类不能被声明为 sealed。
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20170917
{
abstract class Sharp
{
public abstract int area();
}
class New1 : Sharp
{
private int length;
private int width;
public New1()
{
length = 3;
width = 4;
}
public override int area()
{
return length * width;
}
}
class New2 : Sharp {
private int length;
private int width;
public New2()
{
length = 3;
width = 4;
}
public override int area()
{
return length * width / 2;
}
}
class Program
{
static void Main(string[] args)
{
New1 n1 = new New1();
Console.WriteLine(n1.area());
New2 n2 = new New2();
Console.WriteLine(n2.area());
Console.ReadKey();
}
}
}
当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。虚方法是使用关键字 virtual 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。
动态多态性是通过 抽象类 和 虚方法 实现的。
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20170917
{
class Sharp
{
protected int length;
protected int width;
public Sharp(int a,int b){
length =a;
width=b;
}
public virtual int area()
{
Console.WriteLine("父类的面积");
return 0;
}
}
class new1 : Sharp
{
public new1(int a,int b) : base(a,b) { }
public override int area()
{
return length * width;
}
}
class new2 : Sharp
{
public new2(int a,b) { }
public override int area()
{
return length * width / 2;
}
}
class Program
{
static void Main(string[] args)
{
new1 n1 = new new1(3,4);
new2 n2 = new new2(3,4);
Console.WriteLine(n1.area());
Console.WriteLine(n2.area());
Console.ReadKey();
}
}
}
Base 是子类中引用父类
This 是当前类,引用自己 1、尽量少用或者不用base和this。除了避开子类的名称冲突和在一个构造函数中调用其他的构造函数之外,base和this的使用容易引起不必要的结果。
2、在静态成员中使用base和this都是不允许的。原因是,base和this访问的都是类的实例,也就是对象,而静态成员只能由类来访问,不能由对象来访问。
3、base是为了实现多态而设计的。
4、使用this或base关键字只能指定一个构造函数,也就是说不可同时将this和base作用在一个构造函数上。
5、简单的来说,base用于在派生类中访问重写的基类成员;而this用于访问本类的成员,当然也包括继承而来公有和保护成员。
6、除了base,访问基类成员的另外一种方式是:显示的类型转换来实现。只是该方法不能为静态方法。 希望我的回答对你有帮助,如果方便请设为满意答案。
多态笔记:
C# 多态性
多态:一个接口多个功能。
静态多态性:编译时发生函数响应(调用);
动态多态性:运行时发生函数响应。
静态绑定(早期绑定):编译时函数和对象的连接机制。
两种技术实现静态多态性:函数重载/运算符重载。
函数重载:在同一范围内对相同函数名有多个定义,可以是参数类型或参数个数的不同,但不许只有返回值类型不同。
运算符重载:
关键字 abstract 声明抽象类:用于接口部分类的实现(派生类继承抽象类时,实现完成)。抽象类包含抽象方法,抽象方法可被派生类实现。
抽象类规则:
1.不能创建抽象类的实例2.不能在抽象类外定义抽象方法3.不能把抽象类声明为sealed(类前带关键字sealed代表该类是密封类,不能被继承)关键字virtual声明虚方法:用于方法在继承类中的实现(在不同的继承类中有不同的实现)。
抽象类和虚方法共同实现动态多态性。
注:继承类中的重写虚函数需要声明关键字 override,在方法参数传入中写(类名 形参名)例如 public void CallArea(Shape sh),意思是传入一个 shape 类型的类。