“方法必须具有返回类型”

时间:2015-08-03 18:49:21

标签: c#

“方法必须具有返回类型”关于公共发送(SerialPort serialPort1)。我特别想念的是什么?这是我想开始写入com端口的部分。通过在线查看其他问题,我注意到我可能缺少该类的汇编引用或正文部分。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEST_Listbox
{
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        comboBox1.Items.Add(new Command { DisplayText = "Part 1", CommandText = "01P00101##" });
        comboBox1.Items.Add(new Command { DisplayText = "Part 2", CommandText = "02P00102##" });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = "COM3";
        serialPort1.BaudRate = 9600;
        serialPort1.Parity = Parity.None;
        serialPort1.DataBits = 8;
        serialPort1.StopBits = StopBits.One;
        serialPort1.Handshake = Handshake.None;
        serialPort1.RtsEnable = true;
        serialPort1.DtrEnable = true;

        serialPort1.Open();
        if (serialPort1.IsOpen)
        {
            serialPort1.WriteTimeout = 500;
            button1.Enabled = false;
        }        
    }

    public class Command
    {
        public string DisplayText { get; set; }
        public string CommandText { get; set; }

        public Send(SerialPort serialPort1)
        {
            if (serialPort1.IsOpen) 
            {
                var content = new List<byte>();
                content.Add(2);
                content.AddRange(Encoding.ASCII.GetBytes(CommandText));
                content.Add(3);
                byte[] buffer = content.ToArray();
                serialPort1.Write(buffer, 0, buffer.Length);
            }
        }

        public override string ToString()
        {
            return DisplayText;
        }
    }


    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var command = (Command)comboBox1.SelectedItem;
        if (command != null)
        {
            command.Send(serialPort1);
        }
    }

 }
}

2 个答案:

答案 0 :(得分:3)

这意味着您的发送方法没有返回类型。这意味着你不会在该方法中返回任何内容。如果该方法不能返回任何内容,则只需添加void作为返回类型:

public void Send(SerialPort serialPort1)
    {
        if (serialPort1.IsOpen) 
        {
            var content = new List<byte>();
            content.Add(2);
            content.AddRange(Encoding.ASCII.GetBytes(CommandText));
            content.Add(3);
            byte[] buffer = content.ToArray();
            serialPort1.Write(buffer, 0, buffer.Length);
        }
    }

答案 1 :(得分:0)

在C#中,除了Constructor / Destructor之外,类的所有方法都有一个返回类型。否则,返回类型为void

由于您的Send()被编码为不返回任何内容,因此您从方法标题中删除void

自:

public Send(SerialPort serialPort1)

要:

public void Send(SerialPort serialPort1)