C#重载和重写

Overload:重载就是在同一个类中,方法名相同,参数列表不同.参数列表不同包括:参数的个数不同,参数类型不同.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace OverLoading
 6 {
 7     class Program
 8     {
 9         public static int max(int i, int j)                    //静态方法
10         {
11             if (i > j)
12                 return i;
13             else
14                 return j;
15         }
16         public static double max(double i, double j)        //重载静态方法
17         {
18             if (i > j)
19                 return i;
20             else
21                 return j;
22         }
23         static void Main()
24         {
25             Console.WriteLine(max(1, 2));
26             Console.WriteLine(max(1.1, 120.02));
27             Console.ReadLine();
28         }
29     }
30 }

代码分析:
在上述示例中,虽然有多个max方法,但由于方法中参数类型不相同,当在程序中调用max方法时,就会自动去寻找能匹配相应参数的方法。
运行上述代码,其输出结果如图4.3所示。
同名的重载方法之间是通过其参数的数量、类型和顺序来区分的,只要这3种属性的任意一种不同,就可以定义不同的方法。例如:
int methodName(int i, double j)
int methodName(int i, double j, int k)
int methodName(int i, int j)
int methodName(double i, int j)

OverRide:说的是两个类继承,子类重写父类的方法,在调用的时候,子类的方法会覆盖父类的方法,也就是会调用子类的方法.在父类中的方法必须有修饰符Virtual,而在子类的方法中必须知名OverRide.(方法名称必须相同,参数也要相同)重写格式:

 1 //父类中
 2 public virtual void Method()
 3 {
 4 
 5 }
 6 //子类中:
 7 public override void Method()
 8 {
 9 
10 }

重写以后,用父类对象和子类对象访问Method()方法,结果都是访问在子类中重新定义的方法,父类中的方法相当于备覆盖掉了.子类中为满足自己的需要来重复定义某个方法的不同实现.

posted @ 2014-07-03 13:52  SkyTeam_LBM  阅读(282)  评论(0编辑  收藏  举报