1

我刚开始使用 Yaml,非常感谢一些输入。我正在创建一个 YAML 并尝试将其脱轨到现有的 C# 类。现有的 C# 类:

    [System.Xml.Serialization.XmlIncludeAttribute(typeof(FooType))]

    public partial class BarType {

       private int barVariable;

       public Int Bar {
        get {
            return this.barVariable;
        }
        set {
            this.barVariable = value;
        }
    }


    }

    public partial class FooType : BarType {

       private string fooVariable;
       public string Foo {
        get {
            return this.fooVariable;
        }
        set {
            this.fooVariable = value;
        }
    }


[System.Xml.Serialization.XmlRootAttribute("HeadType", Namespace="xyz", IsNullable=false)]

public partial class HeadType {

    private BarType[] barTypesField;

    [System.Xml.Serialization.XmlArrayItemAttribute("FooService", typeof(FooType), IsNullable=false)]

      public BarType[] BarTypes {
          get {
                return this.barTypesField;
              }
           set {
                this.barTypesField = value;
               }
            }

现在我有一个 Yaml,

HeadType:
  - Bar: 0
  - Bar: 29

当我尝试反序列化上述 Yaml 时,我没有收到任何错误。

但是当我将我的 Yaml 更改为类似下面的内容时,它并不知道标签 Foo。

HeadType:
  - Bar: 0 
    Foo: FooTest

有没有办法可以做到这一点?我已经尝试了以下也不起作用:

HeadType:
  FooType:
    - Bar: 0
      Foo: FooTest

我正在使用 Yaml 点网序列化“YamlDotNet.Serialization”,这就是序列化的工作方式:

    Deserializer deserializer = new Deserializer();
    var result = deserializer.Deserialize<RootType>(yamlInput1);

其中 Root 是包含 HeadType 的类。

4

1 回答 1

0

尝试使用

HeadType:
  - !bar
    Bar: 0
  - !foo
    Bar: 0
    Foo: FooTest

YamlDotNet 不会根据存在的内容来推断实际的类型,因此您需要通过标签告诉它是哪种类型。加载时,需要向反序列化器注册这些标签:

deserializer.RegisterTagMapping("!bar", typeof(BarType));
deserializer.RegisterTagMapping("!foo", typeof(FooType));
于 2017-03-06T10:13:30.570 回答