C# 支撑2种情势的多态性: 编译时的多态性、运行时的多态性
编译时的多态性:
编译时的多态性是经由过程重载来完成的
要领重载
您能够在统一个范围内对雷同的函数名有多个定义。函数的定义必需相互差别,能够是参数列表中的参数范例差别,也能够是参数个数差别。不能重载只要返回范例差别的函数声明。写个例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class exchange //定义一个exchange类 {//要领完成交流两参数数据 public void swap(int a, int b) { int temp; temp = a; a = b; b = temp; Console.WriteLine("{0},{1}",a,b); } public void swap(string a, string b) { string temp; temp = a; a = b; b = temp; Console.WriteLine("{0},{1}", a, b); } } class program { static void Main(string[] args) { exchange exch = new exchange(); exch.swap(10, 20); //挪用 swap(int a,int b)要领 exch.swap("大", "小"); //挪用 swap(string a,string b)要领 } } }
效果:
操纵符重载
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class student //定义student类 { private int Chinese; private int Math; public void value(int a, int b) //定义一个赋值的要领,今后学了组织要领就不这么麻烦了 { Chinese = a; Math = b; } public static student operator + (student a, student b) //运算符重载,完成相加功用 { student stu = new student(); stu.Chinese = a.Chinese + b.Chinese; stu.Math = a.Math + b.Math; return stu; } public int getChinese() //猎取Chinese 的要领 { return Chinese; } public int getMath() //猎取Math 的要领 { return Math; } } class program { static void Main(string[] args) { student a = new student(); student b = new student(); a.value(70,80); b.value(40, 50); student stu = a + b; //70+40, 80+50 Console.WriteLine("a+b Chinese = {0}\na+b Math = {1}", stu.getChinese(), stu.getMath()); } } }
效果:
运行时的多态性:
运行时的多态是指直到体系运行时,才依据实际情况决议完成何种操纵,C#中运行时的多态经由过程笼统类或虚要领来完成的。
笼统类和笼统要领
C# 许可您运用关键字 abstract 建立笼统类或笼统要领,当一个派生类继续自该笼统类时,完成即完成。笼统类包括笼统要领,笼统要领可被派生类完成。派生类具有更专业的功用。笼统类不能够被实例化,
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test {//建立笼统类和笼统要领 abstract class score { public abstract int Add(); } //建立子类 class student : score { private int Chinese = 80; private int Math = 90; public override int Add() //关键字 override 实例要领 { int sum=Chinese+Math; return sum; } } class program { static void Main(string[] args) { student stu = new student(); Console.WriteLine(stu.Add() ); //效果 170 } } }
虚要领
虚要领是运用关键字 virtual 声明的。虚要领能够在差别的继续类中有差别的完成。对虚要领的挪用是在运行时发作的。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class score { protected int Chinese = 80; protected int Math = 90; public virtual int Add() //定义一个虚要领 { int sum = Chinese + Math; return sum; } } //定义子类,完成要领 class student : score { public override int Add() //关键字 override 实例要领,完成相减操纵 { int sub = Math - Chinese ; return sub; } } class program { static void Main(string[] args) { student stu = new student(); Console.WriteLine(stu.Add() ); //效果 10 } } }
我们能够看出运行时真正挪用的要领并非虚要领,而是override 实例后的要领
以上就是 C#进修日志23---多态性 之 运算符重载、要领重载、笼统类、虚要领的内容,更多相关内容请关注ki4网(www.ki4.cn)!