首页 > 代码库 > c#继承中的函数调用
c#继承中的函数调用
首先看下面的代码:
using System; namespace Test { public class Base { public void Print() { Console.WriteLine(Operate(8, 4)); } protected virtual int Operate(int x, int y) { return x + y; } } }
namespace Test { public class OnceChild : Base { protected override int Operate(int x, int y) { return x - y; } } }
namespace Test { public class TwiceChild : OnceChild { protected override int Operate(int x, int y) { return x * y; } } }
namespace Test { public class ThirdChild : TwiceChild { } }
namespace Test { public class ForthChild : ThirdChild { protected new int Operate(int x, int y) { return x / y; } } }
namespace Test { class Program { static void Main(string[] args) { Base b = null; b = new Base(); b.Print(); b = new OnceChild(); b.Print(); b = new TwiceChild(); b.Print(); b = new ThirdChild(); b.Print(); b = new ForthChild(); b.Print(); } } }
看结果:
从结果中可以看出:使用override重写之后,调用的函数是派生的最远的那个函数,使用new重写则是调用new之前的派生的最远的函数,即把new看做没有重写似的。
c#继承中的函数调用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。