无法使用YamlDotNet序列化KeyValuePair(Unable to serialize a KeyValuePair with YamlDotNet)

编程入门 行业动态 更新时间:2024-10-20 20:32:17
无法使用YamlDotNet序列化KeyValuePair(Unable to serialize a KeyValuePair with YamlDotNet)

我正在编写一个简单的类来序列化我的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; } }

但它仍然无效。

I'm writing a simple class that serializes my IConfiguration interface which has the following method

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

In my class I have a method

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

But the Serializer doesn't write anything to the stream. Somewhere I read that KeyValuePair is not serializable, but this isn't the case anymore now (it was in .NET 2.0)

I tried first converting the IEnumerable to a List (using .ToList()), but nothing's changed. Then I tried creating a class to use instead of 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; } }

But it still doesn't work.

最满意答案

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

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

注意:默认情况下,处理StreamWriter也会关闭基础流。 如果要保持打开状态,请使用带有leaveOpen参数的StreamWriter构造函数重载,并leaveOpen参数传递true。

This is because you don't dispose the StreamWriter, so it isn't flushed to the stream. Try putting it in a using block:

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

Note: by default, disposing the StreamWriter will also close the underlying stream. If you want to keep it open, use the StreamWriter constructor overload that takes a leaveOpen parameter, and pass true for this parameter.

更多推荐

本文发布于:2023-08-07 19:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   YamlDotNet   KeyValuePair   serialize   Unable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!