【问题标题】:C# Ref Parameter [duplicate]C# 参考参数 [重复]
【发布时间】:2018-10-01 19:51:09
【问题描述】:

函数长这样是什么意思?

 bool Connect([ref string  errormessage])
 {
     \\Code
 }

我这样称呼它吗?

 string error = "";
 if(!<MyInstance>.Connect(error))
       MessageBox.Show(error);

【问题讨论】:

标签: c#


【解决方案1】:

假设函数调用如下,因为上面有语法错误。

bool Connect(ref string errormessage)
{
    \\Code
}

那么,这意味着

参数错误消息作为引用而不是值传递。

当参数作为引用传递时:

  1. 参数必须在传递之前进行初始化。
  2. 方法定义和调用方法都必须显式 使用 ref 关键字。
  3. 对被调用方法中参数的任何更改(即错误消息)都会反映在参数(即错误)中 调用方法。

string error = ""; //Point 1  
if(!<MyInstance>.Connect(ref error)) //Point 2 


bool Connect(ref string errormessage) //Point 2
{
    errormessage = "Error Occurred"; 
    // At this moment the value of error becomes 'Error Occurred' since 
    // it was passed by reference - Point 3
}

关于语法错误,[ref string errormessage] 将给出语法错误,因为它不是有效的attribute,即[Optional] string errormessage

此外,使用带有ref 的可选属性没有多大用处,因为通过 ref 传递的参数不能有默认值。

来源:MSDN

【讨论】:

  • Nit:在第 3 点中,您的意思是“对参数的任何更改”。我本来只是编辑它,但我不确定它是否合适。 (参数出现在调用代码中;在方法中它只是参数。所以ref error是一个参数,errormessage是一个参数。)
  • 谢谢,这肯定是合适的。
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 2023-03-28
  • 2011-01-21
  • 1970-01-01
  • 2012-11-22
  • 2015-08-06
相关资源
最近更新 更多