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()
{ …Run Code Online (Sandbox Code Playgroud) 以下代码:
class B
{
public bool FinishedDownloading { get; set; } = false;
};
class A
{
public B DownloadStream { get; set; }
};
A a = new A();
Console.WriteLine(a.DownloadStream?.FinishedDownloading != false);
Console.WriteLine(a.DownloadStream?.FinishedDownloading == true);
Run Code Online (Sandbox Code Playgroud)
输出:
True
False
Run Code Online (Sandbox Code Playgroud)
如何在地球上a.DownloadStream?.FinishedDownloading != false的true时候DownloadStream是null和FinishedDownloading是false?!
让我们忘记发生的事情并关注结果.
我们知道这种说法a.DownloadStream?.FinishedDownloading != false是正确的,因为它不是false,所以在我们的宇宙中,当某些东西是真的那么它应该是真的,因为1 == 1,对吧?
那么为什么当我们做a.DownloadStream?.FinishedDownloading == true结果时现在是假的?!疯狂.
我想我知道这里发生了什么.这是因为当DownloadStream null然后FinishedDownloading布尔值无法访问时,因此左侧为空,所以C#"认为":
a.DownloadStream?.FinishedDownloading != false
好的,让我们检查一下null值是否等于boolean"false"值.嗯,肯定没有,所以让我们输出真实.
a.DownloadStream?.FinishedDownloading == …