问题描述
我有以下项目依赖结构:
I have the following project dependency structure:
_visualizerTests.dotnetcore
-- .NET Core 2.2Visualizer.2019
-- .NET Framework 4.7.2
_visualizerTests.dotnetcore
-- .NET Core 2.2Visualizer.2019
-- .NET Framework 4.7.2
在 .NET Framework 项目中,我定义了以下类型:
In the .NET Framework project, I have the following type defined:
[Serializable] public struct EndNodeData { public string Closure { get; set; } public string Name { get; set; } public string Type { get; set; } public string Value { get; set; } }
当我尝试在 .NET Core 项目中序列化此类型时:
When I try to serialize this type in the .NET Core project:
var endnodeData = new EndNodeData { Closure = null, Name = null, Type = "int", Value = "5" }; var stream = File.Create(Path.GetTempFileName()); var formatter = new BinaryFormatter(); formatter.Serialize(stream, endnodeData);
我收到以下异常:
System.TypeLoadException:无法从程序集mscorlib,版本=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"中加载类型System.Runtime.CompilerServices.IsReadOnlyAttribute".'
.NET Framework 项目中定义的类类型序列化没有问题,.NET Core 项目中定义的值类型也是如此.
Class types defined in the .NET Framework project serialize without a problem, as do value types defined in the .NET Core project.
我该如何解决这个问题?
(这是我上一个问题的后续.)
删除
bin
和obj
文件夹并删除解决方案的.vs
文件夹没有帮助.Deleting the
bin
andobj
folders, and deleting the solution's.vs
folder doesn't help.我已在 .NET Core 存储库中提交了问题.>
I've filed an issue on the .NET Core repo.
推荐答案
这可能已在 .NET Core 3 中修复,但在此之前,可以使用以下解决方法:
This has presumably been fixed in .NET Core 3, but until then, the following workarounds are available:
- 避免自动实现的属性;改用完整的属性或公共字段.(为了抑制编译器警告,我使用了
[SuppressMessage("", "IDE0032", Justification = "https://github.com/dotnet/core/issues/2981")]
for这个目的. - 在同一个程序集或一些公共程序集中定义自定义
System.Runtime.CompilerServices.IsReadOnlyAttribute
.
- Avoid auto-implemented properties; use full properties, or public fields instead. (In order to suppress the compiler warning, I used
[SuppressMessage("", "IDE0032", Justification = "https://github.com/dotnet/core/issues/2981")]
for this purpose. - Define a custom
System.Runtime.CompilerServices.IsReadOnlyAttribute
in the same assembly or some common assembly.
这篇关于从引用的 .NET Framework 项目序列化值类型期间 .NET Core 项目中的 TypeLoadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!