Why string value remains unchanged after calling function

This question already has an answer here:

  • Passing Objects By Reference or Value in C# 7 answers

  • Because you're changing the value of the parameter that's passed in, not the original value.

    ie str becomes a copy of x when you pass it in. Changing that makes no difference to the value stored in x .

    EDIT: Ok, that was an overly simplified explanation, but as pointed out, better explanations are already available. Tim's right, strings are immutable, so you can't change the contents of the string that's stored in that reference, you can only replace it with a new one, but unless you specifically specify the parameter as 'ref', you can't change that reference inside the method.


    It's not just strings, you also won't be able to change objects to be new objects, ie, this won't work:

    static void Change(ClassA aObj) 
    {
        aObj = new ClassA(); // Won't hold when you leave the function
    }
    

    The reason is that you are passing the reference of those parameters by value. That means you get to see and mess around with what's there, but you can't change it to point to a new reference slot in the memory.

    In order to fix that, you need to use the ref / out keywords.

    For a more elaborate explanation, read this.


    尝试传递关键字ref的字符串:

    static void Change(ref string str)
    {
        str = "Test";
    }
    
    链接地址: http://www.djcxy.com/p/21012.html

    上一篇: C#数组参数引用

    下一篇: 调用函数后为什么字符串值保持不变