Seeking guidance reading .yaml files with C#

前端 未结 3 827
长发绾君心
长发绾君心 2021-01-18 08:37

Two months later: The YAML (Eve Online blueprint.yaml) file I tried to parse changed a huge deal which also made it much easier to parse using de deserializer. If someone (f

3条回答
  •  借酒劲吻你
    2021-01-18 08:58

    Your question has already been correctly answered, but I would like to point out that your approach is probably not the best one for parsing files. The YamlDotNet.RepresentationModel.* types offer an object model that directly represents the YAML stream and its various parts. This is useful if you are creating an application that processes or generates YAML streams.

    When you want to read a YAML document into an object graph, the best approach is to use the Deserializer class. With it you can write your code as follows:

    using(var reader = File.OpenText("blueprints.yaml")
    {
        var deserializer = new Deserializer();
        var blueprintsById = deserializer.Deserialize>(reader);
    
        // Use the blueprintsById variable
    }
    

    The only difference is that the Id property of the YamlBlueprint instances won't be set, but that's just a matter of adding this:

    foreach(var entry in blueprintsById)
    {
        entry.Value.Id = entry.Key;
    }
    

提交回复
热议问题