我是否使用 ref 正确传递我的参数?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能使用
ref
传递临时值,因为被调用的方法必须能够分配给调用者的变量。你为什么要使用它?您永远不会分配给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 toCOMMPORT
.Why not just:
除非您打算修改调用者传递的实际变量,否则无需传递
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.仅当传递具有可用引用的内容时,才能使用
ref
。这意味着您必须首先声明一个变量,然后通过 ref 传递该变量: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: