【问题标题】:Method Parameters with ref not working [duplicate]带有ref的方法参数不起作用[重复]
【发布时间】:2016-06-20 14:52:59
【问题描述】:

我正在尝试捕获异常并将这些值传递给另一个方法,但我得到 必须使用 'ref' 关键字传递参数 '1'必须使用 ref 或 out 参数是一个可赋值的变量并且与 abc.AbendProgram(ref string, ref System.Exception) 匹配的最佳重载方法有一些无效参数。请帮忙,因为我不确定我犯了什么错误。

private void OpenDatabases()
{

     try
     {
          WinDSSS.connectionString = 
          ConfigurationManager.AppSettings["WinDSS_Connection"].Replace("%DrivePath%", DrivePath);

     }
     catch (Exception ex)
     {
          logger.AddEntry(TFSUtilities.Logger.EventType.Fatal, 
                    "frmMain.OpenDatabases", "Exception", ref ex);
          AbendProgram(ref "Open Database", ref ex);
     }

}

private void AbendProgram(ref string theRoutine, ref Exception theException)
{
     int errorNumber = -1;
     string ErrorDesc = "Unknown Error";
     if ((theException != null))
     {
          errorNumber = 9999;
          ErrorDesc = theException.ToString();
          if ((theException.InnerException != null))
          {
               ErrorDesc = ErrorDesc + Constants.vbCrLf + 
                          theException.InnerException.Message;
          }
     }

     System.Windows.Forms.MessageBox.Show("There was an error in RSCShell:" +
          theRoutine + Constants.vbLf + Constants.vbLf + Constants.vbLf + 
          "Error " + errorNumber + " - " + ErrorDesc + 
          Constants.vbLf + Constants.vbLf + "Please contact SUPPORT to resolve this issue");
     System.Environment.Exit(0);
}

【问题讨论】:

  • 创建一个字符串变量并将其提供给您的“AbendProgram”方法。错误消息告诉您出了什么问题。 ref 或 out 参数必须是可分配的变量。我建议您从方法定义中完全删除 ref - 您没有正确使用它。
  • 参数不必是ref参数。无论如何,您永远不会在方法内更改它们的值。
  • 正如@Dennis_E 指出的那样,您为什么要使用ref 关键字?

标签: c# asp.net ref


【解决方案1】:

AbendProgram 接受一个引用字符串。当您传入 ref "open database" 时,这是一个无法分配的常量文字字符串。您需要传入一个字符串变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2023-03-29
    • 2011-08-06
    • 2021-10-26
    • 2016-03-17
    相关资源
    最近更新 更多