我编写了一个C#代码,它将函数(1-9)发送到微控制器,控制器将通过RS232(SERIAL PORT)将数据发送回我的计算机。我遇到的问题是我试图获取传入的数据并将其放入排序列表中。排序列表键将是日期/时间,值将是传入数据。我试图将sortedlist部分添加到我的代码中,但它没有成功。我得到的错误是:
错误CS1503参数2:无法从'int'转换为'serialreadwrite.SMCValues'
CS0162检测到无法访问的代码SMCData-
我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Timers;
using System.IO;
using System.Net;
using System.Threading;
namespace serialreadwrite
{
public class SMCValues
{
public string ArrayVoltage;
public string ArrayCurrent;
public string AutoMPPT;
public string MotorVoltage;
public string ArrayAmps;
public string MaxMotorVoltage;
public string MotorRPM;
public string SerialNumber;
public string SMCType;
class Program
{
static void Main(string[] args)
{
SerialPort _serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
_serialPort.RtsEnable = true;
_serialPort.DtrEnable = true;
_serialPort.Open();
for (int i = 0; i < 10; i++)
{
string c = Convert.ToString(i);
byte[] array_out = Encoding.ASCII.GetBytes(c); //convert i to the right variable type;
_serialPort.Write(array_out, 0, array_out.Length);
byte[] array_out2 = new byte[1];
array_out2[0] = 0xD;
_serialPort.Write(array_out2, 0, array_out2.Length);
//print what you receive
int k = 0;
int reader = 0;
string fullstring = "";
while (k < 23)
{
reader = _serialPort.ReadByte();
fullstring += Convert.ToChar(reader);
k++;
DateTime cur = DateTime.Now;
SortedList<DateTime, SMCValues> mySL1 = new SortedList<DateTime, SMCValues>();
Console.WriteLine(" (mySL1):");
while (true)
{
for (int j = 0; j < 10; j++)
{
string p = Convert.ToString(j);
cur = DateTime.Now;
mySL1.Add(cur, j); // j is throwing the errror
System.Threading.Thread.Sleep(1000);
}
foreach (KeyValuePair<DateTime, SMCValues> kvp in mySL1)
{
Console.WriteLine("my first key is = {0}, and my first value is = {1}", kvp.Key, kvp.Value);
}
Thread.Sleep(5000);
}
Console.WriteLine(fullstring);
_serialPort.DiscardInBuffer();
_serialPort.DiscardOutBuffer();
}
Console.ReadLine();
}
}
}
}
}
答案 0 :(得分:0)
您正在尝试将整数值'j'分配给作为类的'SMCValues'。
从您的问题看来,您最初是在尝试验证您是否可以获得有效日期的排序列表,因此您可以暂时进行以下更改:
//SortedList<DateTime, SMCValues> mySL1 = new SortedList<DateTime, SMCValues>();
SortedList<DateTime, int> mySL1 = new SortedList<DateTime, int>();
你也需要改变你的foreach。
然后在您准备好之后,交换回原始声明,并确保在.Add语句中使用'SMCValues'