2016-11-09 64 views
-2

我正在開發一個將OutGauge數據傳輸到Arduino的控制檯應用程序,但我遇到了下面描述的問題。如何訪問創建方法之外的實例?

這裏是我的代碼的頂部:

using System; 
using InSimDotNet.Out; 
using ArduinoDriver; 
using ArduinoUploader.Hardware; 
using ArduinoDriver.SerialProtocol; 

class Program 
{ 
    static void Main() 
    { 
     var driver = new ArduinoDriver.ArduinoDriver(ArduinoModel.NanoR3, true); 

我需要訪問driver(我在Main方法創建)在outgauge_PacketReceived()。 具體而言,我需要使用它的Send()方法。

static void outgauge_PacketReceived(object sender, OutGaugeEventArgs e) 
{ 
    //I need driver.Send() here. 
} 
+2

使'driver'成爲您的類的成員爲'MyDriverClass driver = ...'。 – HimBromBeere

回答

4

在類級別聲明driver

static ArduinoDriver _driver; 

static void Main() 
{ 
    _driver = new ArduinoDriver.ArduinoDriver(ArduinoModel.NanoR3, true); 
    //... 
} 

你聲明爲一個類的成員,則仍然實例化它Main

0

聲明它主要之外,像這樣:

using System; 
using InSimDotNet.Out; 
using ArduinoDriver; 
using ArduinoUploader.Hardware; 
using ArduinoDriver.SerialProtocol; 

class Program 
{ 
    ArduinoDriver driver; 

    static void Main() 
    { 
    driver = new ArduinoDriver.ArduinoDriver(ArduinoModel.NanoR3, true); 
相關問題