2013-04-09 48 views
1

我見過這個問題問了幾次,似乎無法得到我的頭爲什麼這是行不通的。請幫助noob(並且溫柔!)。我只是試圖創建一個類來接受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"); 
     } 
    } 
} 
+6

請同時顯示調用代碼給你的錯誤,不僅是Conex類。 – 2013-04-09 23:52:59

+0

有兩種類型都叫做Conex?與您在此展示的課程在同一個程序集中進行施工的代碼是? – 2013-04-10 00:00:37

+0

檢查您是否編譯了該項目 - 如果它被「遺漏」,則在配置管理器中取消選中 – NSGaga 2013-04-10 01:27:00

回答

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例程中,你其實可以嘗試打開和關閉它扔在我的電腦上一個異常的連接(因爲它沒有「COM5」端口):

static void Main(string[] args) { 
    Conex abc = new Conex("COM5"); 
    abc.Open(); 
    abc.Close(); 
} 
+0

謝謝!我發現我的骨頭移動 - 我正在使用原始的.cs文件,而且它沒有更新到我在測試程序中放置的引用 - 難怪這是拋出參數錯誤! – Nick 2013-04-10 18:21:09

相關問題