奇怪的引用行为(与 int 相同的内存地址)
嘿! 我现在正在学习引用类型,但我不明白为什么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"));
}
}
Hy!
Iam learning refference types now, and I dont get it why does x has the same memory address as y? Shouldn't they have different addresses?
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"));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Main
中的x
和y
是独立变量。它们可以存储不同的值。他们不能位于同一地址。请注意,它们是值类型变量 - 在这段代码中您实际上根本没有了解引用类型,因为它使用任何引用类型(除了字符串
、程序
和控制台
)。但是,您的代码并没有显示这一点 - 它显示的是
DisplayMemAddress
中的参数的地址,这是完全不同的。x
和y
的值按值传递到该方法中。如果您将DisplayMemAddress
方法中的参数重命名为z
,将会很有帮助:现在更容易讨论了。您显示的是
z
的地址,而不是x
或y
。该地址将位于堆栈上(作为实现细节),并且由于两次调用中堆栈的高度相同,因此它将显示相同的值。现在,如果您将方法更改为使用引用传递,您实际上将看到x
和y
的地址:老实说,显示地址并不是学习引用类型、值类型和参数传递(IMO)的最佳方式。
我有几篇文章您可能会觉得有用:
x
andy
inMain
are independent variables. They can store different values. They can't be at the same address. Note that they're value type variables though - you're not actually learning about reference types at all in this code, as it doesn't use any reference types (exceptstring
,Program
andConsole
).However, your code doesn't show that - it's showing the address of the parameter in
DisplayMemAddress
, which is entirely different. The values ofx
andy
are passed by value into the method. It would be helpful if you'd rename the parameter in yourDisplayMemAddress
method toz
:Now it's easier to talk about. You're displaying the address of
z
, notx
ory
. That address will be on the stack (as an implementation detail) and as the stack is the same height in both calls, it'll show the same value. Now if you change the method to use pass-by-reference, you'll actually see the address ofx
andy
:To be honest, showing addresses isn't the best way of learning about reference types, value types and parameter passing IMO.
I have a couple of articles you might find useful though: