如何访问创建它的方法之外的实例?

时间:2016-11-09 16:27:31

标签: c#

我正在开发一个将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 个答案:

答案 0 :(得分:4)

在班级宣布driver

static ArduinoDriver _driver;

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

您将其声明为类成员,然后仍在Main

中实例化它

答案 1 :(得分:0)

在Main之外声明它,如下所示:

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);