一个(可能)简单的解释——构造函数定义和参数
本文关键字:构造函数 定义 参数 解释 可能 简单 一个 | 更新日期: 2023-09-27 18:08:34
我已经看到这个问题被问了几次了,似乎不能理解为什么这不起作用。请帮助一个新手(而且要温柔!)我只是想创建一个类来接受COM端口的名称,然后在该端口上启动一个串行对象。我一直得到"Conex不包含接受1个参数的构造函数"错误,尽管在我看来这就是它所包含的全部。想法吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace Conex_Commands
{
public class Conex
{
string NewLine = "'r";
int BaudRate = 921600, DataBits = 8, ReadTimeout = 100, WriteTimeout = 100;
Parity Parity = Parity.None;
StopBits StopBits = StopBits.One;
public Conex(string PortName)
{
SerialPort Serial = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
Serial.ReadTimeout = ReadTimeout;
Serial.WriteTimeout = WriteTimeout;
Serial.NewLine = NewLine;
}
}
}
main中包含的调用代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Conex_Commands;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
Conex abc = new Conex("COM5");
}
}
}
这只是为了调试的目的吗?
我的VS2010代码显示此代码没有错误。
然而,它是无用的,因为只要你调用Conex
的构造函数,SerialPort
就会回到作用域之外。
相反,将您的Serial
对象置于构造函数之外:
public class Conex {
string NewLine = "'r";
int BaudRate = 921600, DataBits = 8, ReadTimeout = 100, WriteTimeout = 100;
Parity Parity = Parity.None;
StopBits StopBits = StopBits.One;
SerialPort Serial;
public Conex(string PortName) {
Serial = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
Serial.ReadTimeout = ReadTimeout;
Serial.WriteTimeout = WriteTimeout;
Serial.NewLine = NewLine;
}
public void Open() {
Serial.Open();
}
public void Close() {
Serial.Close();
}
}
现在,从您的Main
例程中,您实际上可以尝试打开和关闭连接(在我的PC上抛出异常,因为它没有"COM5"端口):
static void Main(string[] args) {
Conex abc = new Conex("COM5");
abc.Open();
abc.Close();
}