开发者

How can I display the actual value of a reference in C#

I'm in the process of learning more about C# and am wondering how to display the actual value of a reference or the address of a struct. I'm looking for is something analogous to the following C code:

    int i; 
    printf("int i re开发者_开发百科sides at memory location %x",&i);


In an unsafe context, this will work in C#:

int i = 10;
int *ptr = &i;
Console.WriteLine((int)ptr);

I don't know if it can be done in a safe context, or, if so, how (I suspect it can't).


This cannot be done in C#, that I am aware of. .NET takes the liberty of moving pieces of storage around as it sees fit, and so the address of a variable holds only temporary meaning at best.


Although you can do this in some contexts, the result is largely meaningless. As has been noted, References are not addresses - or at least, they don't have to be. So what you are attempting, even if it works, isn't guaranteed over all implementations, and isn't usually particularly useful. If you don't pin, the value isn't reliable, and if you do pin you change the very thing you are reporting...

Really, you should be using different tools outside the language for this... windbg+SOS, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜