在C#中传递引用类型 [英] Passing reference type in 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, butmyString = 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 toFunc
, whereFunc
parametermyString
will start pointing to that location. Later when youAppend
a text to that location, it gets added. But later when you assignnull
tomyString
, 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 letS1
refers to that object.In Step 2, after passing
S1
toFunc
, nowmyString
also points to the same object in memory.Later when you
Append
, text throughmyString
, it updates the original object, sincemyString
is pointing to the memory location held by the object.In Step 3, when you assign null to the
myString
it looses the address forStringBuilder
object, but this doesn't change anything in the object or the pointerS1
.这篇关于在C#中传递引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!