【发布时间】:2020-06-19 05:57:09
【问题描述】:
我正在使用启用了新功能的 C# 8,具有此代码 sn-p:
[Serializable]
class Inner
{
public readonly int mI;
public readonly string s = "abc"; // doesn't compile
public Inner(int i) { mI = i; }
}
[Serializable]
class Outter
{
public readonly List<Inner> li = new List<Inner>() // doesn't compile
{
new Inner(2),
new Inner(3)
};
}
它没有编译并说:
Field s 是可序列化的 Inner 类型的成员,但它是不可序列化的字符串类型的成员。
和
字段 li 是可序列化的 Outter 类型的成员,但属于不可序列化的 System.Collections.Generic.List 类型。
那么为什么它说“字符串”不能被序列化,我的代码有什么问题,我该如何解决?
我收到此错误是因为我的项目为代码分析设置了“Directory.build.target”规则集,如下所示:
真的 8.0 使能够 错误的
<PropertyGroup>
<RootPath>$(MSBuildThisFileDirectory.TrimEnd("\").TrimEnd("/"))</RootPath>
<OutputFolder>$(RootPath)/out</OutputFolder>
<DropOutputFolder>$(OutputFolder)/drop</DropOutputFolder>
</PropertyGroup>
<PropertyGroup>
<Include>xxxxx</Include>
<ExcludeByAttribute>ObsoleteAttribute,GeneratedCodeAttribute,CompilerGeneratedAttribute</ExcludeByAttribute>
</PropertyGroup>
错误来自代码分析器:
Error CA2235 Field li is a member of type Outter which is serializable but is of type System.Collections.Generic.List<NUnitTestProject_core.Inner> which is not serializable
希望这次很清楚。谢谢
【问题讨论】:
-
你能分享你得到的编译器错误吗?我最终无法重现它
-
我也没有编译错误!您使用的是哪个版本的 .NET?
-
请向我们展示更多代码 c# 有几十个序列化器,其中许多支持原生数据注释,如
Serializable。 -
没有 ReadOnly 是否可以工作?
-
看来,您收到了CA2235 警告。为什么将其视为错误?我认为它与 C# 8 无关
标签: c# string list serialization compilation