我试图了解如何通过"引用"分配给c#中的类字段.
我有以下示例要考虑:
public class X
{
public X()
{
string example = "X";
new Y( ref example );
new Z( ref example );
System.Diagnostics.Debug.WriteLine( example );
}
}
public class Y
{
public Y( ref string example )
{
example += " (Updated By Y)";
}
}
public class Z
{
private string _Example;
public Z( ref string example )
{
this._Example = example;
this._Example += " (Updated By Z)";
}
}
var x = new X();
Run Code Online (Sandbox Code Playgroud)
运行上面的代码时,输出是:
X(由Y更新)
并不是: …
为什么使用此代码:
unsafe
{
for (int i = 0; i < 10; i++)
{
Double w = new Double();
Console.WriteLine((IntPtr)(&w));
}
}
Run Code Online (Sandbox Code Playgroud)
我总是得到相同的号码?如何在循环中创建新变量?有了新地址吗?
原因,为什么这对我来说是个问题,我需要生成一个随机的双数,然后我在两个对象中使用一个指针(引用那个双).在其中一个对象我正在改变这个值,我希望它也改变其他对象:)