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

时间:2016-06-05 07:35:20

标签: c# yaml yamldotnet

这是我的简单类,其中DigitalStorage是二进制可串联类。它的源代码可以在这里找到:

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

1 个答案:

答案 0 :(得分:1)

如果您只是在implicit operator课程中添加DigitalStorage,那么它将从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);
    }
}