MutableSlab
和ImmutableSlab
实现之间的唯一区别是readonly
应用于handle
字段的修饰符:
using System;
using System.Runtime.InteropServices;
public class Program
{
class MutableSlab : IDisposable
{
private GCHandle handle;
public MutableSlab()
{
this.handle = GCHandle.Alloc(new byte[256], GCHandleType.Pinned);
}
public bool IsAllocated => this.handle.IsAllocated;
public void Dispose()
{
this.handle.Free();
}
}
class ImmutableSlab : IDisposable
{
private readonly GCHandle handle;
public ImmutableSlab()
{
this.handle = GCHandle.Alloc(new byte[256], GCHandleType.Pinned);
}
public bool IsAllocated => this.handle.IsAllocated;
public void Dispose()
{
this.handle.Free();
}
}
public static void Main()
{
var mutableSlab = new MutableSlab();
var immutableSlab = new ImmutableSlab();
mutableSlab.Dispose();
immutableSlab.Dispose();
Console.WriteLine($"{nameof(mutableSlab)}.handle.IsAllocated = {mutableSlab.IsAllocated}");
Console.WriteLine($"{nameof(immutableSlab)}.handle.IsAllocated = {immutableSlab.IsAllocated}");
}
}
但它们会产生不同的结果:
mutableSlab.handle.IsAllocated = False
immutableSlab.handle.IsAllocated = True
GCHandle 是一个可变结构,当您复制它时,它的行为与immutableSlab
.
修饰符是否会readonly
创建字段的隐藏副本?这是否意味着它不仅仅是编译时检查?我在这里找不到有关此行为的任何信息。这种行为是否记录在案?