在 C# (.NET) 中使用 YAML:YamlDotNet 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 C# (.NET) 中使用 YAML:YamlDotNet 库



YAML(YAML Ain't Markup Language)是一种方便的数据序列化格式,常用于配置文件、CI/CD 流水线描述、Docker Compose 和 Kubernetes 清单。在 .NET 生态系统中,用于处理 YAML 的主要库是 YamlDotNet——一个功能强大、性能卓越且完全兼容 YAML 1.1 和 1.2 规范的工具。



在本文中,我们将介绍:如何安装 YamlDotNet,如何对 C# 对象执行基本的序列化和反序列化,如何配置自定义标签以及如何处理复杂的数据结构。



安装 YamlDotNet



该库可通过 NuGet 获取。在包管理器控制台中执行以下命令:



dotnet add package YamlDotNet


或者通过 Package Manager Console:



Install-Package YamlDotNet


基本用法:将 YAML 反序列化为 C# 对象



假设我们有一个包含应用程序设置的 YAML 文件 config.yaml:



app:  name: MyApp  version: 2.0.1  debug: truedatabase:  host: localhost  port: 5432  credentials:    user: admin    password: secret


创建相应的 C# 类:



public class AppConfig{    public string Name { get; set; }    public string Version { get; set; }    public bool Debug { get; set; }}

public class DatabaseConfig{ public string Host { get; set; } public int Port { get; set; } public CredentialsConfig Credentials { get; set; }}

public class CredentialsConfig{ public string User { get; set; } public string Password { get; set; }}

public class RootConfig{ public AppConfig App { get; set; } public DatabaseConfig Database { get; set; }}


现在将 YAML 反序列化为对象:



using YamlDotNet.Serialization;using YamlDotNet.Serialization.NamingConventions;

var yamlContent = File.ReadAllText("config.yaml");

var deserializer = new DeserializerBuilder() .WithNamingConvention(UnderscoredNamingConvention.Instance) // 用于 snake_case .Build();

var config = deserializer.Deserialize<RootConfig>(yamlContent);

Console.WriteLine(config.App.Name); // MyAppConsole.WriteLine(config.Database.Port); // 5432


将 C# 对象序列化为 YAML



反向操作——将 C# 对象转换为 YAML 字符串:



var config = new RootConfig{    App = new AppConfig { Name = "MyApp", Version = "2.0.1", Debug = true },    Database = new DatabaseConfig    {        Host = "localhost",        Port = 5432,        Credentials = new CredentialsConfig { User = "admin", Password = "secret" }    }};

var serializer = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) // YAML 中使用 camelCase .Build();

var yaml = serializer.Serialize(config);Console.WriteLine(yaml);


结果:



app:  name: MyApp  version: 2.0.1  debug: truedatabase:  host: localhost  port: 5432  credentials:    user: admin    password: secret


处理集合和复杂类型



YamlDotNet 完美支持列表、字典和嵌套结构。列表示例:



public class Project{    public string Name { get; set; }    public List<string> Tags { get; set; }}

// YAML:// name: MyProject// tags:// - dotnet// - yaml// - csharp

var yaml = @"name: MyProjecttags: - dotnet - yaml - csharp";

var deserializer = new DeserializerBuilder().Build();var project = deserializer.Deserialize<Project>(yaml);

foreach (var tag in project.Tags) Console.WriteLine(tag);


自定义标签和类型(TagMapping)



有时 YAML 文件包含显式标

推荐