将自身引用为 属性 的 class 序列化问题

Issue serializing a class that references itself as a property

说这个我的 class 是通过递归调用生成的:

public class Level
{
    public string Name { get; set; }
    public string Value { get; set; }
    public List<Level> NextLevel { get; set; }
    public Level()
    {
        NextLevel = new List<Level>();
    }
}

然而,当我尝试将其序列化为 xml 时,我收到此错误:

The type System.Collections.Generic.List`1[[....ResponseModel+Level, Testing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context.

我试过Json序列化,没问题。

我认为 NextLevel 属性 有问题。这里需要特殊属性吗?

我没有找到太多关于这个的信息。

要使用 XML 序列化来序列化 lists/arrays,您通常必须将 XmlArray and XmlArrayItem 属性应用到您的 属性 以指定它应该将其序列化为XML 个元素的嵌套序列:

[XmlArray("NextLevel")]
[XmlArrayItem("Level")]
public List<Level> NextLevel { get; set; }