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看做沒(méi)有重寫似的。
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
Unity向量按照某一點(diǎn)進(jìn)行旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Unity向量按照某一點(diǎn)進(jìn)行旋轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
C#使用Parallel類進(jìn)行多線程編程實(shí)例
這篇文章主要介紹了C#使用Parallel類進(jìn)行多線程編程的方法,實(shí)例分析了Parallel類的相關(guān)使用技巧,需要的朋友可以參考下2015-06-06
C#中Winfrom默認(rèn)輸入法的設(shè)置方法
這篇文章主要介紹了C#中Winfrom默認(rèn)輸入法的設(shè)置方法,以實(shí)例形式較為詳細(xì)的分析了C#中輸入法設(shè)置的相關(guān)技巧,需要的朋友可以參考下2015-05-05

