Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 跨类访问方法_C#_Class - Fatal编程技术网

C# 跨类访问方法

C# 跨类访问方法,c#,class,C#,Class,我希望能够从“AtCommand”类访问“Uart”类中的方法。i、 e.AT命令类通过串行端口向调制解调器发送和接收命令。我无法理解为什么Uart中的方法在“AtCommand”中不可用,但如果我尝试从主窗体访问它们,它们是可用的 这是两个类的代码,注意:GsmPort下有扭曲的红线。写入并警告它在当前上下文中不可用(所以我假设范围问题) } } 和AtCommand: namespace ClassLessons { class AtCommand { Uar

我希望能够从“AtCommand”类访问“Uart”类中的方法。i、 e.AT命令类通过串行端口向调制解调器发送和接收命令。我无法理解为什么Uart中的方法在“AtCommand”中不可用,但如果我尝试从主窗体访问它们,它们是可用的

这是两个类的代码,注意:GsmPort下有扭曲的红线。写入并警告它在当前上下文中不可用(所以我假设范围问题)

} }

和AtCommand:

namespace ClassLessons
{
    class AtCommand
    {
        Uart GsmPort = new Uart();
        GsmPort.Write("Test");
    }
}

您正在方法外部调用
GsmPort.Write(“Test”)
。您可能需要以下内容:

namespace ClassLessons
{
    class AtCommand
    {
        Uart GsmPort = new Uart();
        public AtCommand()
        {
            GsmPort.Write("Test");
        }
    }
}

您需要将Uart和AtCommand都设置为公共的类

您的端口字段是私有的:

更改:

SerialPort port = new SerialPort();
致:


它将在其他类中公开访问。

尝试将您的类声明为
公共类Uart{…
GsmPort.Write(“Test”);
不在方法中,您只能调用
方法或
构造函数中的方法
SerialPort port = new SerialPort();
public SerialPort port = new SerialPort();