【问题标题】:A (probably) simple explanation - constructor definition and argument(s)(可能)简单的解释 - 构造函数定义和参数
【发布时间】:2013-04-09 23:50:24
【问题描述】:

我已经看到这个问题被问了几次,但我似乎无法理解为什么这不起作用。请帮助一个菜鸟(并且要温柔!)。我只是想创建一个类来接受 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");
         }
    }
}

【问题讨论】:

  • 请同时显示给您错误的调用代码,而不仅仅是 Conex 类。
  • 是否有两种类型都命名为 Conex?与您在此处显示的类在同一程序集中进行构造的代码吗?
  • 检查您是否编译了项目 - 如果它被“遗漏”,则在配置管理器中未选中
  • 添加了调用 - 它肯定正在编译并在配置管理器中检查。

标签: c# class constructor


【解决方案1】:

这只是为了调试目的吗?

我的 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();
}

【讨论】:

  • 谢谢!我发现了我的愚蠢举动 - 我正在使用原始 .cs 并且它没有更新到我在测试程序中放置的引用 - 难怪它会抛出参数数量错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多