我是否使用 ref 正确传递我的参数?

发布于 2024-09-06 04:51:30 字数 676 浏览 3 评论 0原文

SMSCOMMS SMSEngine = new SMSCOMMS("COM6");

该代码似乎没有将我的 COM6 参数作为有效的ref string。我该如何解决这个问题?

public class SMSCOMMS
{
   public SMSCOMMS(ref string COMMPORT)
   {
    SMSPort = new SerialPort();
    SMSPort.PortName = COMMPORT;
    SMSPort.BaudRate = 9600;
    SMSPort.Parity = Parity.None;
    SMSPort.DataBits = 8;
    SMSPort.StopBits = StopBits.One;
    SMSPort.Handshake = Handshake.RequestToSend;
    SMSPort.DtrEnable = true;
    SMSPort.RtsEnable = true;
    SMSPort.NewLine = System.Environment.NewLine;
    ReadThread = new Thread(
        new System.Threading.ThreadStart(ReadPort));
}
SMSCOMMS SMSEngine = new SMSCOMMS("COM6");

The code doesn't seem to take my argument of COM6 as a valid ref string.How can I solve this?

public class SMSCOMMS
{
   public SMSCOMMS(ref string COMMPORT)
   {
    SMSPort = new SerialPort();
    SMSPort.PortName = COMMPORT;
    SMSPort.BaudRate = 9600;
    SMSPort.Parity = Parity.None;
    SMSPort.DataBits = 8;
    SMSPort.StopBits = StopBits.One;
    SMSPort.Handshake = Handshake.RequestToSend;
    SMSPort.DtrEnable = true;
    SMSPort.RtsEnable = true;
    SMSPort.NewLine = System.Environment.NewLine;
    ReadThread = new Thread(
        new System.Threading.ThreadStart(ReadPort));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

初心 2024-09-13 04:51:30

您不能使用 ref 传递临时值,因为被调用的方法必须能够分配给调用者的变量。你为什么要使用它?您永远不会分配给COMMPORT

为什么不只是:

public SMSCOMMS(string COMMPORT)

You can't pass a temporary with ref, because the called method must be able to assign to the caller's variable. Why are you using it to begin with? You never assign to COMMPORT.

Why not just:

public SMSCOMMS(string COMMPORT)
无可置疑 2024-09-13 04:51:30

除非您打算修改调用者传递的实际变量,否则无需传递 ref 参数。由于您无法修改字符串文字(根据定义,它是常量),因此它对于按引用传递无效。

There's no need to pass a ref param unless you're intending to modify the actual variable the caller's passed. Since you can't modify a string literal (it's constant, by definition), it's not valid for passing by reference.

恋竹姑娘 2024-09-13 04:51:30

仅当传递具有可用引用的内容时,才能使用 ref。这意味着您必须首先声明一个变量,然后通过 ref 传递该变量:

string comm = "COM6";
SMSCOMMS SMSEngine = new SMSCOMMS(ref comm);

You can only use ref when you are passing something that has a usable reference. That means you have to declare a variable first, then pass that variable by ref:

string comm = "COM6";
SMSCOMMS SMSEngine = new SMSCOMMS(ref comm);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文