如何判断不同作用域中两个变量的引用相等?
假设您正在调试。在某一时刻,您处于方法 A 中,该方法具有 Foo
类型的参数 foo。稍后您将进入方法 B,该方法也采用 Foo
类型的参数 foo。
这两个变量很可能是同一个 Foo
实例,但是你怎么知道呢?由于它们处于不同的作用域,因此您无法调用 ReferenceEquals()
。有没有什么方法可以获取变量指向的实际内存位置,以便您可以判断它们是否是实例?
Let's say you are debugging. At one point you are in Method A, which has a parameter foo of type Foo
. Later on you are in Method B, which also takes a parameter foo of type Foo
.
These two variables may well be the same Foo
instance, but how do you tell? Because they are in different scope, you cannot call ReferenceEquals()
. Is there some way you can obtain the actual memory location the variables point to so that you can tell if they are the instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信您可以使用
Make Object ID
功能。有关此内容的更多信息,请访问此处,但是总结一下:“标记”对象后,您将在第二次调用 Foo 时看到分配的 ID。
I believe you can use the
Make Object ID
feature. More information on this can be found here, but to summarize:After you "mark" the object, you will see the assigned ID in the second call to Foo.
在调试器中,您可以将对第一个方法中的对象的引用存储到静态字段,然后将第二个方法中的变量与静态字段进行比较。
While in the debugger, you could store a reference to the object in the first method to a static field and then compare the variable in the second method to the static field.
好吧,您可以获得指向变量的指针,但这需要在不安全的块中运行。
一旦你“不安全”,你可以像这样声明一个指向你的 Foo 的指针:
这已经在 SO 中讨论过:
C#内存地址和变量
well you could get a pointer to your variable but this requires to run in an unsafe block.
once you are "unsafed" you can declare a pointer to your Foo like this:
this has been already discussed here in SO:
C# memory address and variable
作为 Mark Cidade 建议的改进,在第一种方法中,在立即窗口中键入以下内容:
然后,在第二种方法中,键入以下内容:
立即窗口将显示测试结果。
不过,CodeNaked 的建议更好。
As a development of Mark Cidade's suggestion, when inside the first method type the following into the immediate window:
Then, when in the second method, type the following:
The immediate window will display the result of the test.
However, CodeNaked's suggestion is better.