在C#中传递引用类型 [英] Passing reference type in C#

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

问题描述

 类测试
{
静态无效Func键(StringBuilder的myString的)
{
myString.Append(测试);
的myString = NULL;
}
静态无效的主要()
{
StringBuilder的S1 =新的StringBuilder();
Func键(S1);
Console.WriteLine(S1);
}
}



输出为测试,为什么不是它空?



如果S1传递 引用以Func键(),那么为什么 myString.Append(测试)修改它,但的myString = NULL 不?



先谢谢了。


解决方案

如果S1通过引用传递给函数功能( ),那么为什么
myString.Append(测试)不改变它




它不是通过引用传递,而不是它的地址值被传递给函数。



假设 S1 指向一个内存位置0x48,这将被传递到 Func键,其中函数功能参数的myString 将开始指向该位置。后来,当你追加文本到该位置,它被添加。可是后来,当你分配的myString ,它开始指向什么,但原来的位置保持不变。



您应该看到:参数在C#路过乔恩斯基特



考虑下面的图。
在步骤1中,创建类型的新对象的StringBuilder 并让 S1 指对象。





在第2步,合格后 S1 函数功能,现在的myString 还指出,在内存中的同一个对象。





追加,到的myString 文本,它更新了原来的对象之后,因为的myString 指向的对象持有的内存位置。



在步骤3,当你将null分配给的myString 它失去的地址 StringBuilder的对象,但这并不改变对象或指针 S1 东西。




class Test
{
    static void Func(StringBuilder myString)
    {
        myString.Append ("test");
        myString = null;
    }
    static void Main()
    {
        StringBuilder s1 = new StringBuilder();
        Func(s1);
        Console.WriteLine (s1);
    }
}

The output is "Test", why isn't it null?

If s1 is passed by reference to Func(), then why does myString.Append("test") change it, but myString = null does not?

Thanks in advance.

解决方案

if s1 is passed by reference to Func(), then why does myString.Append("test") does change it

Its not passed by references, instead its address value is passed to the function.

Suppose S1 is pointing to a memory location 0x48, This will be passed to Func, where Func parameter myString will start pointing to that location. Later when you Append a text to that location, it gets added. But later when you assign null to myString, it starts pointing to nothing, but the original location remains unchanged.

You should see: Parameter passing in C# by Jon Skeet

Consider the following diagrams. In Step 1, you create a new object of type StringBuilder and let S1 refers to that object.

In Step 2, after passing S1 to Func, now myString also points to the same object in memory.

Later when you Append, text through myString, it updates the original object, since myString is pointing to the memory location held by the object.

In Step 3, when you assign null to the myString it looses the address for StringBuilder object, but this doesn't change anything in the object or the pointer S1.

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

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