将字符串传递给方法-引用类型

时间:2019-11-28 18:44:41

标签: c# .net string

using System;

public class Program
{
    public static void Main()
    {
        var sendingString = "Hello";
        Console.WriteLine(sendingString); // 1. Let's say 'sendingString' would be residing in Heap, say, at location 0004.
        DoComputeString(sendingString); // 2. The pointer 0004 is sent to a method
        Console.WriteLine(sendingString); // 5. The expectation is to print the updated string at location 0004. But obviously it doesn't.
    }

    public static void DoComputeString(string incomingString) // 3. 'string' is a reference type - so this method receives a location pointer to the string '0004'
    {
        incomingString = incomingString + "World"; //4. Some operation is performed on a string located at location 0004. The value of string located at 0004 changes.
    }
}

请按顺序1、2、3、4、5查看评论。

我知道应该有5个原因。

也可以说,如果我们每次尝试将字符串发送到新方法时都继续复制字符串,那么GC是否不必如此频繁地清除内存?

0 个答案:

没有答案