使用 XmlSerializer 序列化简单数组
已经晚了而且完全有可能我错过了一些明显的东西,但它是什么?
我正在尝试创建一个支持属性,该属性显示序列化的 int 数组(然后用于构建队列)。
我很确定这是正确的,但是 getter 总是返回一个空字符串,即使其中有值(并不是说它应该返回一个空字符串。
这是我的代码:
readonly Lazy<XmlSerializer> _queueSerializer = new Lazy<XmlSerializer>(() => new XmlSerializer(typeof(int[])));
[StringLength(1000)]
public string _MostRecentPlayers
{
get
{
var stream = new MemoryStream();
_queueSerializer.Value.Serialize(stream, _mostRecentPlayers.ToArray());
return new StreamReader(stream).ReadToEnd();
}
set
{
if (value.IsEmpty())
{
_mostRecentPlayers.Clear();
return;
}
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value));
var tempQueue = _queueSerializer.Value.Deserialize(stream) as int[];
_mostRecentPlayers.Clear();
tempQueue.ForEach(_mostRecentPlayers.Enqueue);
}
}
readonly Queue<int> _mostRecentPlayers = new Queue<int>(_mostRecentAmountTracked);
Its late and fully possible I'm missing something obvious but what is it?
I'm trying to create a backing property which reveals an int array as serialized (which is then used to build up a Queue).
I'm pretty sure this is right but the getter always return a blank string, even when there are values in there (not that it should ever return a blank string.
Here is my code:
readonly Lazy<XmlSerializer> _queueSerializer = new Lazy<XmlSerializer>(() => new XmlSerializer(typeof(int[])));
[StringLength(1000)]
public string _MostRecentPlayers
{
get
{
var stream = new MemoryStream();
_queueSerializer.Value.Serialize(stream, _mostRecentPlayers.ToArray());
return new StreamReader(stream).ReadToEnd();
}
set
{
if (value.IsEmpty())
{
_mostRecentPlayers.Clear();
return;
}
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value));
var tempQueue = _queueSerializer.Value.Deserialize(stream) as int[];
_mostRecentPlayers.Clear();
tempQueue.ForEach(_mostRecentPlayers.Enqueue);
}
}
readonly Queue<int> _mostRecentPlayers = new Queue<int>(_mostRecentAmountTracked);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还没有倒回流;它位于末尾。在读取之前设置
.Position = 0
。或者更简单,只需序列化为StringWriter
,或者如果您确实想使用MemoryStream
,请从GetBuffer()
传递(超大的)后备数组> 连同.Length
一起转换为Encoding
并调用GetString()
。或者对于 ASCII(参见评论):
此外,除非您不太可能在 exe 中序列化,否则我建议简化为:
最后,请注意,作为抛出一些内容的机制,xml 非常冗长周围的整数。 CSV 看起来更简单(假设您想要文本)。
You haven't rewound the stream; it is positioned at the end. Set
.Position = 0
before reading it. Or easier, just serialize to aStringWriter
, or if you really want to use aMemoryStream
, pass the (oversized) backing array fromGetBuffer()
along with the.Length
to anEncoding
and callGetString()
.or for ASCII (see comments):
Also, unless it is unlikely that you will serialize in the exe, I would suggest simplifying to just:
Finally, note that xml is quite verbose as a mechansim to throw some ints around. CSV would seem a lot simpler (assuming you want text).