当我们在c#中将字符串作为out参数传递时会发生什么[关闭]

问题描述 投票:-2回答:2
class Program
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1="fwer", str2;
        Method(out value, out str1, out str2);
        Console.WriteLine (str1);
        Console.ReadKey();
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }

在上面我正在初始化str1并将str1作为输出并更改调用方法中的值。因为字符串是不可变的。更改它应该创建一个新的字符串对象。但它如何在调用方法中正确打印值,调用方法在调用方法中更改。

提前致谢。

c# asp.net c#-4.0 c#-3.0
2个回答
1
投票

string是不可变的,但您不会更改字符串的内容。您正在创建一个新字符串并用该新字符串替换字符串。

这段代码:

string str1="fwer", str2;
Method(out value, out str1, out str2);

做的相当于:

string str1 = "fwer", str2;
str1 = "I've been returned";
str2 = null;

当您使用out参数时,它通过引用传递参数。

由于字符串已经是引用类型,这意味着传递了对引用的引用。然后,当您在方法中更改它时,您正在更改引用而不是字符串的内容。

考虑str1的初始状态,它引用一个字符串对象。

str1 --> ["fwer"]

当您将其作为参数out string s1传递给方法时,会发生以下情况:

s1 --> str1 --> ["fwer"]

所以s1引用了str1参考,改变它将改变str1引用的内容。

然后这行代码:

s1 = "I've been returned";

使s1引用的项引用字符串“我已被返回”:

s1 --> str1 --> ["I've been returned"]

0
投票

String是具有值类型语义的引用类型。字符串是不可变的。当您将字符串作为out / ref函数参数传递时,它与传递任何其他引用类型没有什么不同。

澄清情况的样本:

void Foo()
{
 string str; //reference to string is created which points to null
 str = "foo";//string object is created and "str" is now points to it   

 Bar(out str);//pass "str" as a reference to reference
}

void Bar(out string str1) //"str1" is like a pseudomin for "str". If you change "str1" the "str" changes to.
{
 str1 = "bar";//new string object is created and both "str1" and "str" pointed to it
}

你更新的问题:

string s1 = "foo"; 
string s2 = s1;

有两个对字符串和单个字符串对象的引用。

s1,s2 - 参考。 “foo”是对象。

引用可以改变,“foo”不能。

不变性意味着没有这样的方法:

s1.SomeMethodChangesStringInnerState();
© www.soinside.com 2019 - 2024. All rights reserved.