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

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

问题描述

我知道,串在C#中是引用类型。这是MSDN。然而,这code没有,因为它应该再工作:

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.

如果您的的传递字符串引用的的参考,它会像您期望的工作:

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");
    }
}

请参阅我的文章参数传递了解更多详情。

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

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