C#——继承[模拟Server类]初始化过程顺序DMEO
生活随笔
收集整理的這篇文章主要介紹了
C#——继承[模拟Server类]初始化过程顺序DMEO
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問(wèn)題描述
模擬一個(gè)服務(wù)類,Server類實(shí)現(xiàn)了服務(wù)器的創(chuàng)建邏輯,子類只要在生成實(shí)例對(duì)象時(shí)傳遞一個(gè)端口號(hào)即可創(chuàng)建一個(gè)監(jiān)聽(tīng)該端口的服務(wù),該代碼意圖如下:
(1)通過(guò)SimpleServer的構(gòu)造函數(shù)接收端口參數(shù)。
(2)子類的構(gòu)造函數(shù)默認(rèn)調(diào)用父類的構(gòu)造函數(shù)。
(3)父類的構(gòu)造函數(shù)調(diào)用子類的getPort方法獲得端口號(hào)。
(4)父類構(gòu)造函數(shù)建立端口監(jiān)聽(tīng)機(jī)制(以Console.WriteLine替代)。
(5)對(duì)象創(chuàng)建完畢,服務(wù)監(jiān)聽(tīng)啟動(dòng),正常運(yùn)行。
運(yùn)行該程序,多運(yùn)行幾次,查看輸出結(jié)果,寫出你認(rèn)為的code?1?–?5的執(zhí)行順序,并解釋原因。
源代碼?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace DEMO2 {/*** 以下代碼模擬一個(gè)服務(wù)類,Server類實(shí)現(xiàn)了服務(wù)器的創(chuàng)建邏輯,子類只要在生成實(shí)例對(duì)象時(shí)傳遞一個(gè)端口號(hào)即可創(chuàng)建一個(gè)監(jiān)聽(tīng)該端口的服務(wù),該代碼意圖如下:*(1)通過(guò)SimpleServer的構(gòu)造函數(shù)接收端口參數(shù)。*(2)子類的構(gòu)造函數(shù)默認(rèn)調(diào)用父類的構(gòu)造函數(shù)。*(3)父類的構(gòu)造函數(shù)調(diào)用子類的getPort方法獲得端口號(hào)。*(4)父類構(gòu)造函數(shù)建立端口監(jiān)聽(tīng)機(jī)制(以Console.WriteLine替代)。*(5)對(duì)象創(chuàng)建完畢,服務(wù)監(jiān)聽(tīng)啟動(dòng),正常運(yùn)行。* 運(yùn)行該程序,多運(yùn)行幾次,查看輸出結(jié)果,寫出你認(rèn)為的code 1 – 5的執(zhí)行順序,并解釋原因。*/abstract class Server{protected const int DEFAULT_PORT = 40000;//code1public Server(){Console.WriteLine("2");int port = getPort();//code2Console.WriteLine("Port: " + port);}protected abstract int getPort();}class SimpleServer : Server{private int port = 100;//code3public SimpleServer(int _port){Console.WriteLine("4");port = _port;//code4}protected override int getPort(){Console.WriteLine("5");return (new Random()).NextDouble() > 0.5 ? port : DEFAULT_PORT;//code5}}class Program{public int i = 0;static void Main(string[] args){Server s = new SimpleServer(1000);/*** code3 => code1 => code2 => code5 => code4* 1)繼承類靜態(tài)成員變量初始化 * 2)繼承類實(shí)例變量初始化 * 3)基類靜態(tài)靜態(tài)成員變量初始化 * 4)基類實(shí)例變量初始化 * 5)基類構(gòu)造方法調(diào)用 * 6)繼承類構(gòu)造方法調(diào)用*/}} }參考文章
https://www.iteye.com/blog/fhuan123-829394
總結(jié)
以上是生活随笔為你收集整理的C#——继承[模拟Server类]初始化过程顺序DMEO的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C#——Ellipse(椭圆)类[继承E
- 下一篇: Spring Boot——统一设置返回J