Bitmap.Save 出现 Null Exception 错误,但已明确实例化

Bitmap.Save erroring with Null Exception and yet it is clearly instantiated

在升级到 Unity 和 Visual Studio 之前,我有一个简单的代码块 运行 没有错误,但是在更新之后完全相同的逻辑引发了 NullReferenceException

调用 BitMap.Save() 时出现异常,但我已验证所有输入都已正确实例化,并且我可以在调试期间检查所有关联对象,但无法识别任何空值。在这种情况下,NullReferenceException 非常不明确,我怀疑它专门链接到 Unity 的更新。

Please do not close for duplicate of "What is a NullReferenceException, and how do I fix it?" like my other one. This seems to be an internal issue either with Bitmap and I am looking for specific guidance on how to resolve this.

Bitmap newBmp = new Bitmap(16, 16);
for (int i= 0; i< 16; i++)
{
    for (int j= 0; j< 16; j++)
    {
         newBmp.SetPixel(i, j, Color.blue);
    }
}
using (MemoryStream ms = new MemoryStream())
{
    newBmp.Save(ms, ImageFormat.Bmp); // Null??
    // do more stuff with ms if it didn't crap out
}

异常详细信息,在 newBmp.Save()

上引发

NOTE: neither newBmp or ms are null, and the logic above it has set each pixel to the color blue.

NullReferenceException: Object reference not set to an instance of an object
System.Drawing.ComIStreamMarshaler+ManagedToNativeWrapper..cctor () (at <556bd4f081384ff9b1658a316bdf6616>:0)
Rethrow as TypeInitializationException: The type initializer for 'ManagedToNativeWrapper' threw an exception.
System.Drawing.ComIStreamMarshaler.MarshalManagedToNative (System.Object managedObj) (at <556bd4f081384ff9b1658a316bdf6616>:0)
System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageCodecInfo encoder, System.Drawing.Imaging.EncoderParameters encoderParams) (at <556bd4f081384ff9b1658a316bdf6616>:0)
System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageFormat format) (at <556bd4f081384ff9b1658a316bdf6616>:0)
(wrapper remoting-invoke-with-check) System.Drawing.Image.Save(System.I

事实证明,我不久前引入 Unity 项目的 System.Drawing.dll 版本与新版本的 Unity 不兼容。我们通过删除 dll 并将“csc.rsp”文件添加到 Assets 文件夹并添加行 -r:System.Drawing.dll 来解决它,我认为它会自动使用适当的版本。