值类型的引用相等 [英] Reference equality of value types
问题描述
我已经做了一些 ref
关键字测试,有一件事我无法理解:
I have made some ref
keyword tests and there is one thing I can't understand:
static void Test(ref int a, ref int b)
{
Console.WriteLine(Int32.ReferenceEquals(a,b));
}
static void Main(string[] args)
{
int a = 4;
Test(ref a, ref a);
Console.ReadLine();
}
为什么此代码显示 False
?我知道 int
是一个值类型,但是在这里它应该将引用传递给同一对象.
Why does this code display False
? I know that int
is a value type but here it should pass references to the same object.
推荐答案
为什么此代码显示
False
?
Because int a
and int b
are being boxed when you call object.ReferenceEquals
. Each integer is boxed inside an object
instance. Thus, you are actually comparing references between two boxed values, which clearly aren't equal.
如果查看为该方法生成的 CIL ,您可以轻松地看到此内容:
You can easily see this if you look at the generated CIL for the method:
Test:
IL_0000: nop
IL_0001: ldarg.0 Load argument a
IL_0002: ldind.i4
IL_0003: box System.Int32
IL_0008: ldarg.1 Load argument b
IL_0009: ldind.i4
IL_000A: box System.Int32
IL_000F: call System.Object.ReferenceEquals
IL_0014: call System.Console.WriteLine
IL_0019: nop
IL_001A: ret
可以使用可验证的CIL(例如,在 @leppie的答案中)来检查存储位置是否相等,或者通过以下方式来实现:不安全
代码:
Checking for storage location equality can be achieved either by using verifiable CIL (such as in @leppie's answer) or by unsafe
code:
unsafe static void Main(string[] args)
{
int a = 4;
int b = 5;
Console.WriteLine(Test(ref a, ref a)); // True
Console.WriteLine(Test(ref a, ref b)); // False;
}
unsafe static bool Test(ref int a, ref int b)
{
fixed (int* refA = &a)
fixed (int* refB = &b)
{
return refA == refB;
}
}
这篇关于值类型的引用相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!