2016-11-15 130 views
0

我想知道什麼是最好的方法。c#twincat傳遞參數給類的構造函數

如果我需要將類傳遞給類構造函數,爲什麼我應該在我的類中使用變量。

例子:

using Beckhoff.App.Ads.Core.Plc; 

Class test() 
{ 
    private static IBAAdsServer AdsServer; 
    private static IBAAdsCncClient _cncClient; 

    public test(IBAAdsServer _adsServer) //constructor 
    { 
     try 
     { 
      AdsServer = _adsServer; 
      _cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC"); 
      _cncClient.Synchronize = true; 
     } 
     catch (Exception Except) 
     { MessageBox.Show("Error ! " + Except.Message); } 
    } 

爲什麼我不能做:

using Beckhoff.App.Ads.Core.Plc; 

Class test() 
{ 
    private static IBAAdsCncClient _cncClient; 

    public test(IBAAdsServer _adsServer) //constructor 
    { 
     try 
     { 
      _cncClient = _adsServer.GetAdsClient<IBAAdsCncClient>("CNC"); 
      _cncClient.Synchronize = true; 
     } 
     catch (Exception Except) 
     { MessageBox.Show("Error ! " + Except.Message); } 
    } 

我想了很多不連接類的使用_adsServer,我該怎麼做是否正確?

感謝您的幫助。

+0

你可以這樣做。一旦構造函數完成,您將失去對它的引用。你爲什麼說你做不到?此外,爲什麼你不只是在班級外面學習'GetAdsClient <...>'並將結果推送到你的班級呢? – bixarrio

+0

是的,這是做到這一點的另一種方式,我確實是這樣做的,但我想知道這是否是一種好方法,或者有更好的方法。謝謝 – Jablonovo

回答

0

好吧,這裏就像我現在做的。

using Beckhoff.App.Ads.Core.Plc; 

Class test() 
{ 
private static IBAAdsServer AdsServer; 
private static IBAAdsCncClient _cncClient; 

public test(IBAAdsServer _adsServer)     //constructor 
{ 
    try 
    { 
     AdsServer = _adsServer; 
     _cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC"); 
     _cncClient.Synchronize = true; 
     Classtocall newClass = ClasstoCall(_cncClient);//Passing the argument directly 
} 
catch (Exception Except) 
    { MessageBox.Show("Error ! " + Except.Message); } 
} 
相關問題