TypeLoadException in .NET Core project during seri

2019-08-21 10:10发布

I have the following project dependency structure:

  • _visualizerTests.dotnetcore -- .NET Core 2.2
    • Visualizer.2019 -- .NET Framework 4.7.2

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; }
}

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);

I get the following exception:

System.TypeLoadException: 'Could not load type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

Class types defined in the .NET Framework project serialize without a problem, as do value types defined in the .NET Core project.

How can I resolve this?

(This is a follow-up to my previous question.)

Deleting the bin and obj folders, and deleting the solution's .vs folder doesn't help.

I've filed an issue on the .NET Core repo.

1条回答
倾城 Initia
2楼-- · 2019-08-21 10:22

This has presumably been fixed in .NET Core 3, but until then, the following workarounds are available:

  • 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.

Feedback on the Roslyn issue

查看更多
登录 后发表回答