【问题标题】:method call inside method with ref keyword使用 ref 关键字在方法内部调用方法
【发布时间】:2017-05-09 11:32:12
【问题描述】:

当尝试在另一个方法中调用方法时遇到问题,该方法将 ref 元素作为参数。方法“replaceWordInLine”创建新行,我在方法“findLine”中调用它。我应该给“replaceWordInLine”方法行参数,只是不知道如何用ref来做。

findLine(string dataFile, ....)
{
  string[] text = System.IO.File.ReadAllLines(dataFile.....;
  foreach(string line in text)
  {
   replaceWordInLine(ref , disconnectors, word, wordBegining);
  }
}


 replaceWordInLine(ref string e, string disconnectors, string word, int wordBegining)
    {
        findWordInLine(e, s, out word, out wordBegining);
        string findWord = word;
        StringBuilder newLine = new StringBuilder();
        e.Remove(word.Length,pr);
        newLine.Append(word + " " + e);
    }

【问题讨论】:

  • replaceWordInLine(ref line, disconnectors, word, wordBegining); ?
  • @AgentFire,试过了。显示错误:不能使用 'line' 作为 ref 或 out 值,因为它是 foreach 迭代变量。
  • 代码不是很完整...s 未定义,disconnectors 未使用,e.Remove(word.Length,pr) 没有意义
  • 然后声明一个局部变量,给它赋值line。定义一个List,在那里收集所有结果。
  • 你们都在提供可以让代码工作的解决方案,但在这种情况下(至少我认为)远非理想。请说明为什么要使用您的解决方案

标签: c# ref


【解决方案1】:
string s = line;
replaceWordInLine(ref s, disconnectors, word, wordBegining);

【讨论】:

  • 正是我在 cmets 中输入的内容太晚了,这就是答案 - 简短而简单。
【解决方案2】:

你可以使用 for i 循环而不是 foreach

这个: 字符串[] 文本 = System.IO.File.ReadAllLines(dataFile.....; foreach(文本中的字符串行) { replaceWordInLine(ref , disconnectors, word, wordBegining); }

会变成:

  string[] text = System.IO.File.ReadAllLines(dataFile.....;
  foreach(int i =0; i<text.Length; i++)
  {
   replaceWordInLine(ref text[i] , disconnectors, word, wordBegining);
  }

你很高兴

【讨论】:

  • Ferreti ,是的,我也想过这个问题,但我想它会逐字逐句地挑选那一行,而使用 foreach 我只会通过一行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2018-12-18
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
相关资源
最近更新 更多