c#繼承中的函數(shù)調(diào)用實(shí)例
本文實(shí)例講述了c#繼承中的函數(shù)調(diào)用方法,分享給大家供大家參考。具體分析如下:
首先看下面的代碼:
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();
}
}
}
運(yùn)行結(jié)果為:
12
4
32
32
32
從結(jié)果中可以看出:使用override重寫之后,調(diào)用的函數(shù)是派生的最遠(yuǎn)的那個(gè)函數(shù),使用new重寫則是調(diào)用new之前的派生的最遠(yuǎn)的函數(shù),即把new看做沒有重寫似的。
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C# 解決datagridview控件顯示大量數(shù)據(jù)拖拉卡頓問題
這篇文章主要介紹了C# 解決datagridview控件顯示大量數(shù)據(jù)拖拉卡頓問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
基于Unity3D實(shí)現(xiàn)仿真時(shí)鐘詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Unity3D模擬實(shí)現(xiàn)一個(gè)簡單是時(shí)鐘效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-01-01
c# HttpWebRequest通過代理服務(wù)器抓取網(wǎng)頁內(nèi)容應(yīng)用介紹
在C#項(xiàng)目開發(fā)過程中可能會(huì)有些特殊的需求比如:用HttpWebRequest通過代理服務(wù)器驗(yàn)證后抓取網(wǎng)頁內(nèi)容,要想實(shí)現(xiàn)此方法并不容易,本文整理了一下,有需求的朋友可以參考下2012-11-11
C#基礎(chǔ)學(xué)習(xí)系列之Attribute和反射詳解
大家在使用Attribute的時(shí)候大多需要用到反射,所以放在一起。下面這篇文章主要給大家介紹了關(guān)于C#基礎(chǔ)學(xué)習(xí)系列之Attribute和反射的相關(guān)資料,文中給出了詳細(xì)的示例代碼供大家參考學(xué)習(xí),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
用C#獲取硬盤序列號(hào),CPU序列號(hào),網(wǎng)卡MAC地址的源碼
用C#獲取硬盤序列號(hào),CPU序列號(hào),網(wǎng)卡MAC地址的源碼...2007-03-03

