C# 字符串引用类型? [英] C# string reference type?

查看:23
本文介绍了C# 字符串引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 C# 中的字符串"是引用类型.这是在 MSDN 上.但是,此代码无法正常工作:

I know that "string" in C# is a reference type. This is on MSDN. However, this code doesn't work as it should then:

class Test
{
    public static void Main()
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(test);
        Console.WriteLine(test);
    }

    public static void TestI(string test)
    {
        test = "after passing";
    }
}

输出应该是传递之前"传递之后",因为我将字符串作为参数传递并且它是引用类型,第二个输出语句应该识别出 TestI 方法中的文本更改.但是,我得到在通过之前"在通过之前",这使得它似乎是通过值而不是引用来传递的.我知道字符串是不可变的,但我不明白这将如何解释这里发生的事情.我错过了什么?谢谢.

The output should be "before passing" "after passing" since I'm passing the string as a parameter and it being a reference type, the second output statement should recognize that the text changed in the TestI method. However, I get "before passing" "before passing" making it seem that it is passed by value not by ref. I understand that strings are immutable, but I don't see how that would explain what is going on here. What am I missing? Thanks.

推荐答案

对字符串的引用是按值传递的.按值传递引用和按引用传递对象之间存在很大差异.不幸的是,在这两种情况下都使用了参考"一词.

The reference to the string is passed by value. There's a big difference between passing a reference by value and passing an object by reference. It's unfortunate that the word "reference" is used in both cases.

如果您do通过by引用传递字符串引用,它将按您的预期工作:

If you do pass the string reference by reference, it will work as you expect:

using System;

class Test
{
    public static void Main()
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(ref test);
        Console.WriteLine(test);
    }

    public static void TestI(ref string test)
    {
        test = "after passing";
    }
}

现在您需要区分对引用所引用的对象进行更改,以及对变量(例如参数)进行更改以使其引用不同的对象.我们不能对字符串进行更改,因为字符串是不可变的,但我们可以用 StringBuilder 代替:

Now you need to distinguish between making changes to the object which a reference refers to, and making a change to a variable (such as a parameter) to let it refer to a different object. We can't make changes to a string because strings are immutable, but we can demonstrate it with a StringBuilder instead:

using System;
using System.Text;

class Test
{
    public static void Main()
    {
        StringBuilder test = new StringBuilder();
        Console.WriteLine(test);
        TestI(test);
        Console.WriteLine(test);
    }

    public static void TestI(StringBuilder test)
    {
        // Note that we're not changing the value
        // of the "test" parameter - we're changing
        // the data in the object it's referring to
        test.Append("changing");
    }
}

有关详细信息,请参阅我关于参数传递的文章.

See my article on parameter passing for more details.

这篇关于C# 字符串引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆