一个(可能)简单的解释 - 构造函数定义和参数

时间:2013-04-09 23:50:24

标签: c# class constructor

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



    }


}

我的主要包含的调用代码是:

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

1 个答案:

答案 0 :(得分:0)

这只是出于调试目的吗?

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