【问题标题】:Unable to serialize a KeyValuePair with YamlDotNet无法使用 YamlDotNet 序列化 KeyValuePair
【发布时间】:2016-02-29 19:26:59
【问题描述】:

我正在编写一个简单的类来序列化我的IConfiguration 接口,该接口具有以下方法

IEnumerable<KeyValuePair<string, object>> GetAllProperties();

在我的课堂上我有一个方法

    public void WriteConfiguration(IConfiguration data, Stream stream)
    {
         new Serializer().Serialize(new StreamWriter(stream), data.GetAllProperties());
    }

Serializer 不会向流中写入任何内容。我在某处读到 KeyValuePair 不可序列化,但现在不再是这种情况了(它在 .NET 2.0 中)

我首先尝试将IEnumerable 转换为List(使用.ToList()),但没有任何改变。然后我尝试创建一个类来代替KeyValuePair

    [Serializable]
    private class Pair<TKey, TValue>
    {
        public Pair() { }

        public Pair(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public TKey Key { get; set; }
        public TValue Value { get; set; }
    }

但还是不行。

【问题讨论】:

  • 似乎对我有用...我怀疑这可能是因为您从未处理过 StreamWriter,因此它从未被刷新。

标签: c# serialization yamldotnet


【解决方案1】:

这是因为您没有释放 StreamWriter,因此它不会被刷新到流中。尝试将其放入 using 块中:

public void WriteConfiguration(IConfiguration data, Stream stream)
{
     using (var writer = new StreamWriter(stream))
     {
         new Serializer().Serialize(writer, data.GetAllProperties());
     }
}

注意:默认情况下,处理StreamWriter 也会关闭底层流。如果要保持打开状态,请使用the StreamWriter constructor overload that takes a leaveOpen parameter,并为此参数传递 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多