2014-07-16 59 views
1

我正在嘗試爲Windows服務創建基類。在創建時,該系統會自動創建:來自Windows服務的基類

 public partial class Service1 : ServiceBase 
    { 
    public class Base //added this to become a Base class 
    { 
     protected override void OnStart(string[] args)//generated code for Service 
     { 
      //a bunch of code here that I create 
     } 
    } 
    } 

,我想獲得這個類:

 public class Derived : Base 
     { 

     void Call(string[] args) 
     { 
      Call test = new Call(); 
      test.OnStart(args);///error says no suitable method found to override 
     } 
     } 

我想這樣做的原因是因爲該服務將與多種類型的數據庫和我的互動想要儘可能多的代碼可重用,每個人都會有相同的OnStart,OnStop等......我試圖在派生類中使用虛擬,受保護,公共的方法。我也無法更改生成的代碼。

如何調用保護覆蓋OnStart?我最終也會有私人成員,所以我不必再提出另一個問題,如果有什麼我需要知道什麼時候打電話給那些也會有所幫助的。

+0

你在Derived類中創建'Dervied'實例而不是訪問'this'實例的任何原因? –

+0

沒有那只是一個腦屁,謝謝 – user3825831

回答

2

在您編輯之後: 您必須繼承ServiceBase。在Service1範圍內簡單創建一個公共類不會創建繼承。正確的定義是:

public class Derived : ServiceBase 
{ 
    protected override void OnStart(string[] args) 
    { 
     //example 
     int x = 1; 

     //call the base OnStart with the arguments 
     base.OnStart(args); 
    } 
} 

然後,你的程序類的內部,你會創造這樣的線束來運行它:

var servicesToRun = new[] 
{ 
    new Derived() 
}; 
ServiceBase.Run(servicesToRun); 

MSDN參考here

受保護的OnStart方法需要的參數string[] args,根據你的代碼。你需要傳遞一個參數數組。

+0

我根據你的評論改變了代碼,那你的意思是?同樣的錯誤.. – user3825831

+0

好吧,所以我很清楚你的答案,「Derived:ServiceBase」不是自動生成的,它是我創建的那個,這是正確的嗎? – user3825831

+0

是的,這是正確的。 –