繁体   English   中英

为什么使用ref关键字在函数调用中传递字符串参数

[英]why to use ref keyword for passing string parameter in function calling

字符串是一种引用类型,所以为什么我们在传递函数调用以在主函数中进行更改时必须在字符串变量之前附加ref关键字,例如:

 using System;    
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

 namespace ConsoleApplication1
 {
    class Program
    {
       static void Main(string[] args)
       {
          string keyword= string.Empty;
          removeWhiteSpacetest(keyword);
          Console.WriteLine("Printing In Main");
          Console.ReadLine();
       }
    }

    private void removeWhiteSpacetest( string keyword)
    {
       string pattern = "\\s+";
       string replacement = " ";
       Regex rgx = new Regex(pattern);

       //white space removal
       keyword = rgx.Replace(keyword, replacement).Trim();
    }
 }

因此,当我通过“酒店管理”时,输出应为“酒店管理”,但是我得到的输出相同,即“酒店管理”,而不是预期的输出“酒店管理”。

但是当我使用列表或其他引用类型的对象时,我得到了预期的结果,即“酒店管理”

按照下面的评论更新通过引用。

当您添加ref关键字时,您正在 传递值, 并将引用传递给基础值,因此可以更改数据的值。 参考变量就像一个指针,而不是值本身

阅读MSDN文章。

实际上,这与参数不可变无关,也与参数是引用类型无关。

您看不到更改的原因是您在函数内为参数分配了新值。

不带refout关键字的参数始终按值传递。
我知道,现在您扬起眉毛,但让我解释一下:
没有使用ref关键字传递的引用类型参数实际上是通过value传递其引用。
有关更多信息,请阅读Jon Skeet的 本文

为了证明我的主张,我创建了一个小程序,您可以复制粘贴该程序以查看自己的情况,也可以简单地检查此小提琴

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        String StringInput = "Input";

        List<int> ListInput = new List<int>();

        ListInput.Add(1);
        ListInput.Add(2);
        ListInput.Add(3);

        Console.WriteLine(StringInput);

        ChangeMyObject(StringInput);

        Console.WriteLine(StringInput);


        Console.WriteLine(ListInput.Count.ToString());

        ChangeMyObject(ListInput);

        Console.WriteLine(ListInput.Count.ToString());



        ChangeMyObject(ref StringInput);

        Console.WriteLine(StringInput);

        ChangeMyObject(ref ListInput);

        Console.WriteLine(ListInput.Count.ToString());



    }

    static void ChangeMyObject(String input)
    {

        input = "Output";
    }

    static void ChangeMyObject(ref String input)
    {

        input = "Output";
    }


    static void ChangeMyObject(List<int> input)
    {

        input = new List<int>();
    }

    static void ChangeMyObject(ref List<int> input)
    {

        input = new List<int>();
    }


}

该程序的输出是这样的:

Input
Input
3
3
Output
0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM