2016-11-15 127 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); } 
} 
相关问题