如何在 YamlDotNet 中指定序列化自定义类型?

How to specify serialize custom type in YamlDotNet?

这是我的简单 class,其中 DigitalStorage 是一个可序列化的二进制文件 class。它的源代码可以在这里找到:

https://github.com/QualiSystems/Toscana/blob/master/Toscana/Domain/DigitalStorage.cs

public class Host
{
    public HostProperties Properties { get; set; }
}

public class HostProperties
{

    [YamlAlias("mem_size")]
    public DigitalStorage MemSize { get; set; }
}

当我尝试反序列化以下 YAML 时,它失败了:

host:
    properties:
        mem_size: 4096 MB

这里是例外:

YamlDotNet.Core.YamlException : (Line: 16, Col: 22, Idx: 396) - (Line: 16, Col: 29, Idx: 403): Exception during deserialization
----> System.InvalidCastException : Invalid cast from 'System.String' to 'Toscana.Domain.DigitalStorage'.
at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(EventReader reader, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) in C:\projects\yamldotnet\YamlDotNet\Serialization\ValueDeserializers\NodeValueDeserializer.cs:line 75

如果您只是将 implicit operator 添加到 DigitalStorage class,它会从 string 转换过来:

public class DigitalStorage
{
    public DigitalStorage(string value)
    {
        // TODO: Do whatever you need to convert the string value.
    }

    public static implicit operator DigitalStorage(string value)
    {
        return new DigitalStorage(value);
    }
}