我有以下代码,我试图通过在操作之前和之后使用
GC.GetTotalAllocatedBytes
来获取使用“is”运算符时分配的内存。当执行 thing is MyStruct
时,我得到分配了 24 个字节,但是当执行 thing is MyStruct meow
时,我得到 0 个字节。
这对我来说看起来很奇怪,我希望两者要么分配,要么不分配。这是预期的结果吗?为什么会这样?或者我有什么遗漏的吗
GC.GetTotalAllocatedBytes
?
interface IInterface {}
struct MyStruct : IInterface {}
class Program
{
static void Main(string[] args)
{
MyStruct a;
Meow(a);
ReadLine();
}
static void Meow<T>(T thing) where T : IInterface
{
long beforeBytes = GC.GetTotalAllocatedBytes(true);
bool isMyStruct = thing is MyStruct; // Allocates 24 bytes
// bool isMyStruct = thing is MyStruct meow; // No allocation?
long afterBytes = GC.GetTotalAllocatedBytes(true);
WriteLine($"Before: {beforeBytes}");
WriteLine($"After: {afterBytes}");
WriteLine($"Diff: {afterBytes - beforeBytes}");
WriteLine();
WriteLine(isMyStruct);
}
}
thing is MyStruct
的输出:
Before: 765712
After: 765736
Diff: 24
True
thing is MyStruct meow
的输出:
Before: 765712
After: 765712
Diff: 0
True
当您使用 is Type 时,您只是检查一个对象是否属于某种类型。 这涉及创建指定类型的临时对象来执行检查。因此,在这种情况下,内存是为此临时对象分配的,因此您在使用 GC.GetTotalAlownedBytes 时会看到内存分配。
但是,当您使用 is 类型变量 时,您并没有创建临时对象。相反,您要检查指定的变量是否属于指定的类型。由于在这种情况下您没有创建任何新对象,因此没有额外的内存分配,因此您会看到分配了 0 个字节。