是否有可能获得参考值?

时间:2014-05-01 19:34:08

标签: c#

对象是"按值传递" (而不是"通过引用传递"正如有些人可能认为的那样)值是参考。出于好奇心,是否有可能获得此参考的价值?我假设这个值是某种虚拟地址。

例如,是否可以获得someInstance的参考值?

    public class Program
    {
        public static void Main()
        {   
            SomeClass someInstance = new SomeClass();   
            SomeMethod(someInstance);
        }

        static void SomeMethod(SomeClass input) {
            //...
        }
    }

1 个答案:

答案 0 :(得分:4)

.NET中的对象没有固定地址,因为它们可以通过GC移动。如果您想获得该地址,则需要告知GC将其与fixed statement相关联。请查看Understanding Memory References, Pinned Objects, and Pointers

您需要在“不安全”模式下使用编译(VS Project->属性 - >构建并检查“允许不安全的代码”)

using System;

internal class Program
{
    private static unsafe void Main(string[] args)
    {
        Point point = new Point { X = 10, Y = 20};
        long a = 1;
        long* pA = &a;

        Console.WriteLine("'a' pointer value: \t{0}", *pA);
        Console.WriteLine("'a' pointer address: \t{0:x16}", (long)pA);
        Console.WriteLine("'point' value: \t\t{0:x16}", *(pA - 1));

        // the location of 'point' on the stack
        long prP = (long)(pA - 1); 
        long* pP = *(long**)prP;
        Console.WriteLine("'point' address: \t{0:x16}", *pP);
        Console.WriteLine("'point.Y' value: \t{0}", *(pP + 1));
        Console.WriteLine("'point.X' value: \t{0}", *(pP + 2));

        Console.ReadLine();
    }
}

internal class Point
{
    public int X;
    public long Y;
}

输出:

'a' pointer value:      1
'a' pointer address:    000000001cb6dfa8
'point' value:          00000000027dd788
'point' address:        000007fe8a0851a8
'point.Y' value:        20
'point.X' value:        10