奇怪的引用行为(int的相同内存地址)

时间:2011-02-26 21:04:18

标签: c# pointers reference int

HY! 我现在正在学习参考类型,我不明白为什么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"));
    }
}

1 个答案:

答案 0 :(得分:5)

x中的{p> yMain是独立变量。他们可以存储不同的值。他们不能在同一个地址。请注意,它们是值类型变量 - 您实际上并未在此代码中了解引用类型,因为它不会使用任何引用类型(除了stringProgramConsole)。

但是,您的代码没有显示 - 它显示DisplayMemAddress参数的地址,这完全不同。 xy的值会按值传递给方法。如果您将DisplayMemAddress方法中的参数重命名为z,将会很有帮助:

static unsafe void DisplayMemAddress(int z)
{
    int* ptr = &z;
    Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}

现在谈论起来更容易。您显示的是z的地址,而不是xy。该地址将在堆栈上(作为实现细节),并且由于堆栈在两个调用中的高度相同,因此它将显示相同的值。现在,如果您更改方法以使用传递引用,那么您实际会看到xy的地址:

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"));
        }
    }
}

老实说,显示地址并不是学习参考类型,值类型和参数传递IMO的最佳方式。

我有几篇你可能会觉得有用的文章: