【问题标题】:Problem returning a variable into a receiving object in C#在 C# 中将变量返回到接收对象时出现问题
【发布时间】: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 不会改变。

标签: c# object return


【解决方案1】:

如果你想在RemoveSpace里面重新赋值给words,你需要通过引用来传递变量:

public static string RemoveSpace(ref string words) // Use ref to pass by reference

然后在 Test 内部,你会这样调用方法:

RemoveSpace(ref words);

不通过引用传递,RemoveSpacewords参数是调用方法中words变量的独立变量,所以重新赋值只会影响RemoveSpace的范围。


通常的方法是在Test 中重新分配从RemoveSpace 返回的字符串:

public static void Test(string words)
{
    words = RemoveSpace(words);

【讨论】:

  • 我通常建议尽可能避免使用ref,除了 RemoveSpace 方法已经返回正确的字符串之外,OP 只是没有使用它。
  • @Jono "我通常建议尽可能避免使用ref" 是的,使用ref 不是建议,它是对为什么重新分配@ 的解释RemoveSpace 中的 987654335@ 不会影响 Test 中的变量。
猜你喜欢
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多