【发布时间】:2021-10-03 04:45:45
【问题描述】:
我在将变量共享给不同对象时遇到了一点问题,我希望了解我做错了什么并找到解决问题的方法,我对使用面向对象编程的编程有点陌生语言(C#),我不知道在细节方面我做错了什么。
我要做的基本上是创建一个方法,该方法接收用户输入的某些单词作为字符串,它从字符串中删除多余的空格并创建一个字符串数组,该数组保存字符串中的每个单词用空格隔开。
这里的问题是“返回词;”在“RemoveSpace()”方法的末尾根本没有将值返回给“Test()”。 (我确保使用调试器检查它是否真的在工作,但 RemoveSpace 函数肯定在工作,只是在方法内,返回值似乎被 Test() 方法忽略了。) (另外,要使用正则表达式,请使用“System.Text.RegularExpressions;”库)
我该怎么办?我已经绞尽脑汁想了一段时间,我没有想法, 非常感谢您的帮助
public static class Reverso
{
static void Main(string[] args)
{
//User inputs the words as a string
string words = Console.ReadLine();
//Activates the Test object
Test(words);
}
public static void Test(string words)
{
//Activates the RemoveSpace object.
//It should receive the returned
//value here, but not working
RemoveSpace(words);
//Takes words into a string array
//seperated by spaces
string[] parts = words.Split(' ');
//Shows the result
Console.WriteLine(words);
}
public static string RemoveSpace(string words)
{
//Using regex in order to remove more
//than 1 space between words and characters
Regex regex = new Regex(@"[ ]{2,}", RegexOptions.None);
words = regex.Replace(words, @" ");
//Should return the value of the word
//to the Test object, *not working*
return words;
}
}
【问题讨论】:
-
你调用了 RemoveSpace 但你没有使用返回值。
-
只是在 Ralf 的基础上构建,字符串是不可变的,对它们的任何修改都会产生一个新对象,原始字符串不会被修改。除非将 words 设置为 RemoveSpace 的返回值,否则 words 不会改变。