gal*_*ris 2 c# int pointers reference
海兰!Iam现在学习refference类型,我不明白为什么x和y具有相同的内存地址?他们不应该有不同的地址吗?
class Program
{
static void Main(string[] args)
{
int x = 10; // int -> stack
int y = x; // assigning the value of num to mun.
DisplayMemAddress(x);
DisplayMemAddress(y);
Console.ReadLine();
}
static unsafe void DisplayMemAddress(int x)
{
int* ptr = &x;
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
}
Run Code Online (Sandbox Code Playgroud)
x而y在Main独立变量.他们可以存储不同的值.他们不能在同一个地址.请注意,他们是值类型变量虽然-您实际上并不了解引用类型都在此代码,因为它不使用任何引用类型(除了string,Program和Console).
然而,你的代码并不表明-它显示的地址参数中DisplayMemAddress,这是完全不同的.的值x和y传递由值入方法.如果您将DisplayMemAddress方法中的参数重命名为z:
static unsafe void DisplayMemAddress(int z)
{
int* ptr = &z;
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
Run Code Online (Sandbox Code Playgroud)
现在谈论起来更容易了.您正在显示地址z,而不是x或y.该地址将在堆栈上(作为实现细节),并且由于堆栈在两个调用中的高度相同,因此它将显示相同的值.现在,如果你改变使用传递通过引用的方法,你会真正看到的地址x和y:
class Program
{
static void Main(string[] args)
{
int x = 10; // int -> stack
int y = x; // assigning the value of num to mun.
DisplayMemAddress(ref x);
DisplayMemAddress(ref y);
Console.ReadLine();
}
static unsafe void DisplayMemAddress(ref int z)
{
fixed (int* ptr = &z)
{
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
说实话,显示地址不是学习参考类型,值类型和参数传递IMO的最佳方式.
我有几篇你可能会觉得有用的文章: