由於 在 中BinaryFormatter,以下 API 在 .NET 5 中被標記為過時。 在程式碼中使用它們會在編譯時產生警告或錯誤 SYSLIB0011 。
- System.Exception.SerializeObjectState
- BinaryFormatter.Serialize
- BinaryFormatter.Deserialize
- Formatter.Serialize(Stream, Object)
- Formatter.Deserialize(Stream)
- IFormatter.Serialize(Stream, Object)
- IFormatter.Deserialize(Stream)
從 .NET 8 開始,BinaryFormatter.Serialize 和 BinaryFormatter.Deserialize 在大多數專案類型執行時會丟出 NotSupportedException。 此外, PreserializedResourceWriter.AddBinaryFormattedResource(String, Byte[], String) 作為 警告 已過時,以下 API 作為 錯誤也已過時:
- System.Runtime.Serialization.Formatter
- System.Runtime.Serialization.IFormatter
- System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
因應措施
如果你正在使用 BinaryFormatter,應該因為它的安全性和可靠性問題而停止使用。 欲了解更多資訊,請參閱 BinaryFormatter 及相關類型使用中的反序列化風險 與 偏好替代方案。
隱藏警告
如果你必須使用過時的 API,可以在程式碼或專案檔案中抑制警告/錯誤。
若要僅抑制單一違規,請將預處理器指示詞新增至來源檔案以停用,然後重新啟用警告。
// Disable the warning.
#pragma warning disable SYSLIB0011
// Code that uses obsolete API.
// ...
// Re-enable the warning.
#pragma warning restore SYSLIB0011
若要隱藏 SYSLIB0011 專案中的所有警告,請將屬性新增至 <NoWarn> 專案檔。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
...
<NoWarn>$(NoWarn);SYSLIB0011</NoWarn>
</PropertyGroup>
</Project>
如需詳細資訊,請參閱隱藏警告。